diff --git a/.github/workflows/ansible-deploy.yml b/.github/workflows/ansible-deploy.yml new file mode 100644 index 0000000000..11befab782 --- /dev/null +++ b/.github/workflows/ansible-deploy.yml @@ -0,0 +1,81 @@ +name: Ansible Deployment + +on: + push: + branches: [ master, main, lab6 ] + paths: + - 'ansible/**' + - '!ansible/docs/**' + - '.github/workflows/ansible-deploy.yml' + pull_request: + branches: [ master, main ] + paths: + - 'ansible/**' + - '!ansible/docs/**' + +jobs: + lint: + name: Ansible Lint + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install dependencies + run: | + pip install ansible ansible-lint + + - name: Run ansible-lint + run: | + cd ansible + ansible-lint playbooks/*.yml + + deploy: + name: Deploy Application + needs: lint + runs-on: ubuntu-latest + if: github.event_name == 'push' + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install Ansible + run: pip install ansible + + - name: Setup SSH key from GitHub Secret + run: | + mkdir -p ~/.ssh + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H ${{ secrets.VM_HOST }} >> ~/.ssh/known_hosts 2>/dev/null || true + + - name: Deploy with Ansible + run: | + cd ansible + echo "${{ secrets.ANSIBLE_VAULT_PASSWORD }}" > /tmp/vault_pass + ansible-playbook playbooks/deploy.yml \ + -i inventory/hosts.ini \ + --vault-password-file /tmp/vault_pass \ + -u ${{ secrets.VM_USER }} + rm /tmp/vault_pass + + - name: Verify Deployment + run: | + sleep 10 + curl -f http://${{ secrets.VM_HOST }}:5000 || exit 1 + curl -f http://${{ secrets.VM_HOST }}:5000/health || exit 1 + + - name: Deployment Success + run: echo "✅ Ansible deployment completed successfully" \ No newline at end of file diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml new file mode 100644 index 0000000000..e7abab9fa7 --- /dev/null +++ b/.github/workflows/python-ci.yml @@ -0,0 +1,99 @@ +name: Python CI/CD + +on: + push: + branches: [ master, lab3 ] + tags: + - 'v*' + pull_request: + branches: [ master ] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.13' + cache: 'pip' + cache-dependency-path: 'app_python/requirements.txt' + + - name: Install dependencies + working-directory: app_python + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + + - name: Lint with flake8 + working-directory: app_python + run: | + pip install flake8 + flake8 app.py --count --select=E9,F63,F7,F82 --show-source --statistics + flake8 app.py --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + + - name: Run unit tests + working-directory: app_python + run: | + pytest tests/ -v --cov=app --cov-report=xml --cov-report=term + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v4 + with: + files: ./app_python/coverage.xml + fail_ci_if_error: false + + - name: Run Snyk to check for vulnerabilities + uses: snyk/actions/python@master + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + with: + args: --file=app_python/requirements.txt --severity-threshold=high --skip-unresolved + + build-and-push: + needs: test + runs-on: ubuntu-latest + if: github.event_name == 'push' + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN }} + + - name: Determine version + id: version + run: | + if [[ "${{ github.ref }}" == refs/tags/v* ]]; then + VERSION=${GITHUB_REF#refs/tags/} + else + VERSION=$(date +%Y.%m.%d) + fi + echo "version=${VERSION}" >> $GITHUB_OUTPUT + echo "Version: ${VERSION}" + + - name: Build and push Docker image + id: docker_build + uses: docker/build-push-action@v5 + with: + context: ./app_python + push: true + tags: | + ${{ secrets.DOCKER_USERNAME }}/devops-info-service:${{ steps.version.outputs.version }} + ${{ secrets.DOCKER_USERNAME }}/devops-info-service:latest + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Image digest + run: echo ${{ steps.docker_build.outputs.digest }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 30d74d2584..70f9c768be 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,52 @@ -test \ No newline at end of file +# === Python === +__pycache__/ +*.py[cod] +*.so +.Python +venv/ +env/ +*.egg-info/ + +# === Terraform === +terraform/.terraform/ +terraform/*.tfstate +terraform/*.tfstate.* +terraform/.terraform.lock.hcl +terraform/terraform.tfvars +terraform/*.tfvars +terraform/labsuser.pem + +# === Pulumi === +pulumi/venv/ +pulumi/__pycache__/ +pulumi/Pulumi.*.yaml + +# === Ansible === +ansible/*.retry +ansible/.vault_pass +ansible/__pycache__/ +ansible/labsuser.pem +ansible/group_vars/.vault_pass + +# === Secrets & Keys === +*.pem +*.key +*.pub +.env +.vault_pass +credentials +secrets/ +authorized_keys + +# === IDE === +.idea/ +.vscode/ +*.swp +*.swo + +# === OS === +.DS_Store +Thumbs.db + +# === Logs === +*.log \ No newline at end of file diff --git a/WORKERS.md b/WORKERS.md new file mode 100644 index 0000000000..dc53f098c5 --- /dev/null +++ b/WORKERS.md @@ -0,0 +1,314 @@ +# Lab 17 — Cloudflare Workers Edge Deployment + +## Task 1 — Cloudflare Setup + +### 1.1 Account and Project Creation +A new Cloudflare account was created, and a Workers project named `edge-api` was initialized using `npm create cloudflare@latest`. The project was configured with the "Hello World" TypeScript template. + +### 1.2 CLI Authentication +The Wrangler CLI was authenticated by running `npx wrangler login`. Verification was successful, as confirmed by the output of `npx wrangler whoami`: + +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler whoami + + ⛅️ wrangler 4.90.0 +─────────────────── +Getting User settings... +👋 You are logged in with an OAuth Token, associated with the email kostikova658@gmail.com. +┌──────────────────────────────────┬──────────────────────────────────┐ +│ Account Name │ Account ID │ +├──────────────────────────────────┼──────────────────────────────────┤ +│ Kostikova658@gmail.com's Account │ 94f7d5ad139a9ee913caf0db9e3f2b1d │ +└──────────────────────────────────┴──────────────────────────────────┘ +``` + +### 1.3 Platform Concepts + +- **Workers Runtime:** A lightweight JavaScript/Wasm serverless environment based on the V8 engine. It runs code at the edge without containers or VMs, enabling extremely fast cold starts. +- **`workers.dev` URLs:** A free subdomain provided by Cloudflare for every Worker, allowing instant public access without needing a custom domain. The format is `my-worker.my-subdomain.workers.dev`. +- **Bindings:** A mechanism to connect a Worker to resources like environment variables (`vars`), encrypted secrets (`secrets`), and key-value storage (`KV namespaces`). This is how configuration and state are managed. + +--- + +## Task 2 — Build and Deploy a Worker API + +### 2.1 Implemented Routes +A simple router was implemented in `src/index.ts` to handle requests to three distinct endpoints: +- `GET /`: A welcome message. +- `GET /health`: A health check endpoint returning `OK` with status 200. +- `GET /info`: An endpoint returning basic deployment metadata as a JSON object. + +### 2.2 Local and Remote Deployment + +**Local Verification:** +The Worker was tested locally using `npx wrangler dev`. The terminal output confirms that all implemented routes responded correctly with a `200 OK` status. + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler dev +... +⎔ Starting local server... +[wrangler:info] Ready on http://127.0.0.1:8787 +[wrangler:info] GET / 200 OK (7ms) +[wrangler:info] GET /favicon.ico 404 Not Found (3ms) +[wrangler:info] GET /health 200 OK (3ms) +[wrangler:info] GET /info 200 OK (4ms) +``` + +**Remote Deployment:** +The Worker was then deployed to the Cloudflare global network using `npx wrangler deploy`. + +- **Public URL:** `https://edge-api.kostikova658.workers.dev` + +**Deployment Output:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler deploy + + ⛅️ wrangler 4.90.0 +─────────────────── +Total Upload: 0.82 KiB / gzip: 0.42 KiB +Worker Startup Time: 4 ms +Uploaded edge-api (7.98 sec) +Deployed edge-api triggers (5.90 sec) + https://edge-api.kostikova658.workers.dev +Current Version ID: 6de8c48b-0422-4f07-91fb-10787bb9eab6 +``` + +### 2.3 Version Control +All changes were committed to Git with the message `feat: implement initial API routes for v1.0.0`, establishing a baseline for future deployments. + +--- + +## Task 3 — Global Edge Behavior + +### 3.1 Edge Metadata Endpoint +A new endpoint `GET /edge` was added to return metadata from the incoming request context (`request.cf`). This object provides information about the Cloudflare data center that handled the request. + +**Code added to `src/index.ts`:** +```typescript +// Edge metadata endpoint +if (url.pathname === '/edge') { + const edgeMetadata = { + colo: request.cf?.colo, + country: request.cf?.country, + city: request.cf?.city, + httpProtocol: request.cf?.httpProtocol, + tlsVersion: request.cf?.tlsVersion, + asn: request.cf?.asn, + }; + return new Response(JSON.stringify(edgeMetadata, null, 2), { + headers: { 'Content-Type': 'application/json' }, + }); +} +``` + +### 3.2 Public Edge Execution Verification +After deploying the new version (`f78bbc5e-b847-44d0-9780-d28241854522`), the `/edge` endpoint was called. The response confirms that the code is running on Cloudflare's global network and has access to request-specific metadata. The request was routed through the Frankfurt data center. + +**JSON Response from `https://edge-api.kostikova658.workers.dev/edge`:** +```json +{ + "colo": "IAD", + "country": "DE", + "city": "Frankfurt am Main", + "httpProtocol": "HTTP/2", + "tlsVersion": "TLSv1.3", + "asn": 210644 +} +``` + +### 3.3 Global Distribution Explained +Cloudflare Workers automatically deploys code to its entire global network of data centers (over 300 cities). When a user makes a request, Cloudflare's Anycast network routes it to the nearest data center. This is fundamentally different from traditional cloud platforms (VMs, PaaS, Kubernetes) where you must manually select specific regions (e.g., `us-east-1`, `eu-west-2`) for deployment. With Workers, there is no "deploy to 3 regions" step because it deploys to *all* regions by default, minimizing latency for users worldwide. + +### 3.4 Routing Concepts + +- **`workers.dev`:** A free, managed subdomain provided by Cloudflare for instant public access to a Worker. It's ideal for development, testing, and simple APIs without needing your own domain. +- **Routes:** A mapping that connects a specific path on a *custom domain* (e.g., `api.mycompany.com/v1/*`) to a specific Worker. This is used for production traffic on your own domains. +- **Custom Domains:** Your own registered domain (e.g., `mycompany.com`) that you add to your Cloudflare account. You can then create Routes to trigger Workers from traffic to that domain. +--- + +## Task 4 — Configuration, Secrets & Persistence + +### 4.1 Environment Variables +A plaintext environment variable `API_VERSION` was defined in `wrangler.jsonc` and used in the `/info` endpoint. + +**`wrangler.jsonc` configuration:** +```jsonc +"vars": { + "API_VERSION": "v1.1.0" +} +``` +**Why not for secrets:** Plaintext variables in `wrangler.jsonc` are committed to version control, making them visible to anyone with repository access. This is a major security risk for sensitive data like API keys or passwords. + +### 4.2 Secrets +Two secrets, `API_KEY` (value: `secret_key1`) and `ADMIN_EMAIL` (value: `admin@example.com`), were created using `npx wrangler secret put`. They are accessible via the `env` object in the Worker but their values are not stored in Git. The `/config` endpoint confirms they are loaded without exposing the `API_KEY` value itself. + +**Verification via `/config` endpoint:** +```json +{ + "apiVersion": "v1.1.0", + "adminEmail": "admin@example.com", + "apiKeyLoaded": "true" +} +``` + +### 4.3 Persistence with Workers KV +A Workers KV namespace named `EDGE_KV` was created using `npx wrangler kv namespace create EDGE_KV` and bound to the Worker in `wrangler.jsonc`. API endpoints `POST /kv/:key` and `GET /kv/:key` were implemented to store and retrieve data. The routing logic was updated to support hyphens in keys. + +**`wrangler.jsonc` binding:** +```jsonc +"kv_namespaces": [ + { + "binding": "EDGE_KV", + "id": "1600409be4814f9aaf1a48fafbb7b263" + } +] +``` + +**Persistence Verification:** +A value was stored and successfully retrieved using PowerShell, confirming the KV binding works. The deployment ID for this version is `e8e167c6-33f9-4e90-bc87-cf0b61655969`. +```powershell +# 1. Store a value +> Invoke-WebRequest -Uri "https://edge-api.kostikova658.workers.dev/kv/test-key" -Method POST -Body "hello from the edge" + +StatusCode : 201 +StatusDescription : Created +Content : Stored value for key: test-key + +# 2. Retrieve the value +> Invoke-WebRequest -Uri "https://edge-api.kostikova658.workers.dev/kv/test-key" + +StatusCode : 200 +StatusDescription : OK +Content : hello from the edge +``` +The value persisted across deployments, as it is stored in Cloudflare's distributed KV store, not in the Worker's ephemeral memory. + +--- + +## Task 5 — Observability & Operations + +### 5.1 Inspecting Logs +A `console.log()` statement was added to the `/health` endpoint to demonstrate logging. The `npx wrangler tail` command was used to view live logs from the deployed Worker. + +**Live Log Output:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler tail +... +Connected to edge-api, waiting for logs... +GET https://edge-api.kostikova658.workers.dev/health - Ok @ 09.05.2026, 22:37:18 + (log) Health check performed at 2026-05-09T19:37:18.373Z +GET https://edge-api.kostikova658.workers.dev/health - Ok @ 09.05.2026, 22:37:28 + (log) Health check performed at 2026-05-09T19:37:28.493Z +``` + +### 5.2 Inspecting Metrics +The Cloudflare dashboard provides real-time metrics for the Worker. I reviewed the **Requests** metric on the "Metrics" tab, which shows the total number of invocations over time (13 requests in the last 24 hours). This is a key indicator of traffic volume and application usage. I also observed the **CPU Time** (0.62ms average) and **Request Duration** (0.91ms average), which confirm the high performance of the Worker. + +![Worker Metrics](./edge-api/screenshots/metrics.png) + +### 5.3 Managing Deployments +Cloudflare Workers maintains a history of all deployments, which can be managed via the dashboard or the Wrangler CLI. + +- **Deployment History:** The `npx wrangler deployments list` command was used to view the history of all deployed versions. The active version before the rollback was `33300607...`. + +- **Rollback via CLI:** A rollback to a previous, stable version (`6de8c48b...`) was performed using the command line. This provides a fast and scriptable way to revert changes in production. + +**Rollback Command Output:** +```powershell +# 1. List deployments to find the target version ID +> npx wrangler deployments list +... +Created: 2026-05-09T19:36:54.696Z +... +Version(s): (100%) 33300607-68c9-49b0-94f2-055d67a6ca5f +... +Created: 2026-05-09T19:15:09.002Z +... +Version(s): (100%) 6de8c48b-0422-4f07-91fb-10787bb9eab6 +... + +# 2. Execute the rollback +> npx wrangler rollback 6de8c48b-0422-4f07-91fb-10787bb9eab6 + + ⛅️ wrangler 4.90.0 +─────────────────── +... +√ Are you sure you want to deploy this Worker Version to 100% of traffic? ... yes +Performing rollback... +│ +╰ SUCCESS Worker Version 6de8c48b-0422-4f07-91fb-10787bb9eab6 has been deployed to 100% of traffic. + +Current Version ID: 6de8c48b-0422-4f07-91fb-10787bb9eab6 +``` +The rollback was instantly applied, and the previously active version (`33300607...`) was replaced by the target version (`6de8c48b...`) in production. + +![Deployment History](./edge-api/screenshots/deployments.png) +![Deployment History](./edge-api/screenshots/history.png) + +After rollback: +![Deployment History](./edge-api/screenshots/rollback.png) +--- + +## Task 6 — Documentation & Comparison + +### 6.1 Deployment Summary + +- **Worker URL:** `https://edge-api.kostikova658.workers.dev` +- **Main Routes:** + - `GET /`: Welcome message + - `GET /health`: Health check + - `GET /info`: Basic deployment info + - `GET /edge`: Edge location metadata + - `GET /config`: Loaded configuration and secrets + - `GET /kv/:key`, `POST /kv/:key`: KV storage operations +- **Configuration Used:** + - **Vars:** `API_VERSION` + - **Secrets:** `API_KEY`, `ADMIN_EMAIL` + - **KV Namespace:** `EDGE_KV` + +### 6.2 Evidence +*(All evidence is detailed in previous tasks)* +- **Cloudflare Dashboard:** Screenshot of metrics is in Task 5 +- **/edge JSON Response:** Included in Task 3 +- **Log/Metrics Screenshot:** Live log output is in Task 5 + +### 6.3 Kubernetes vs Cloudflare Workers Comparison + +| Aspect | Kubernetes | Cloudflare Workers | +| ----------------------- | ------------------------------------------------ | ------------------------------------------------ | +| **Setup complexity** | **High:** Requires cluster setup, networking, YAML | **Low:** `npm create`, `wrangler login` | +| **Deployment speed** | **Slow:** (Minutes) Image build, push, pod pull | **Very Fast:** (Seconds) `wrangler deploy` | +| **Global distribution** | **Manual:** Requires multi-cluster/region setup | **Automatic:** Deploys to 300+ cities by default | +| **Cost (for small apps)** | **High:** ($50+/mo) Nodes, Load Balancers | **Very Low:** Generous free tier | +| **State/persistence** | **Flexible:** PVCs, `emptyDir`, external DBs | **Limited:** Workers KV, Durable Objects | +| **Control/flexibility** | **Total Control:** Any language, OS, binary | **Constrained:** JS/Wasm runtime, API limits | +| **Best use case** | Complex microservices, stateful apps, enterprise | APIs, webhooks, auth, static site middleware | + +### 6.4 When to Use Each + +**Scenarios favoring Kubernetes:** +- You have a large, complex application with many microservices. +- You need full control over the operating system, networking, and specific binaries. +- Your application is stateful and requires complex storage solutions like databases or message queues running in the cluster. +- You are building a platform for other developers in your company. + +**Scenarios favoring Cloudflare Workers:** +- You need to build a fast, globally distributed API with minimal latency. +- Your application is stateless or has simple state needs (key-value). +- You have a small team and want to minimize infrastructure management overhead. +- You are building middleware for a static site, handling authentication, or running A/B tests at the edge. + +**My Recommendation:** +For startups, personal projects, and API-driven services where global low latency is critical, **Cloudflare Workers** is a superior starting point due to its simplicity and cost-effectiveness. For large enterprises with complex, stateful systems and dedicated platform teams, **Kubernetes** remains the standard for its power and flexibility. + +### 6.5 Reflection + +- **What felt easier than Kubernetes?** + Almost everything. The setup (`npm create`), deployment (`wrangler deploy`), secrets management, and instant global distribution were orders of magnitude simpler than managing Kubernetes manifests, clusters, and Ingress controllers. + +- **What felt more constrained?** + The runtime environment. In Kubernetes, I can run any Docker container (Python, Go, Java, etc.). With Workers, I am limited to JavaScript/TypeScript and Wasm. The persistence model (KV store) is also much simpler and less flexible than the variety of storage options in Kubernetes (PVCs, etc.). + +- **What changed because Workers is not a Docker host?** + The entire development mindset shifted. Instead of packaging an OS and application into a Docker image, I wrote code directly against the Cloudflare runtime API. There was no `Dockerfile`, no `docker build`, and no concern for the underlying operating system. The focus was purely on the application logic. + diff --git a/ansible/README.md b/ansible/README.md new file mode 100644 index 0000000000..a9c6722964 --- /dev/null +++ b/ansible/README.md @@ -0,0 +1,2 @@ + +[![Ansible Deployment](https://github.com/sunflye/DevOps-course/actions/workflows/ansible-deploy.yml/badge.svg)](https://github.com/sunflye/DevOps-course/actions/workflows/ansible-deploy.yml) diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg new file mode 100644 index 0000000000..ee2655531e --- /dev/null +++ b/ansible/ansible.cfg @@ -0,0 +1,11 @@ +[defaults] +inventory = inventory/hosts.ini +roles_path = roles +host_key_checking = False +remote_user = ubuntu +retry_files_enabled = False + +[privilege_escalation] +become = True +become_method = sudo +become_user = root \ No newline at end of file diff --git a/ansible/docs/LAB05.md b/ansible/docs/LAB05.md new file mode 100644 index 0000000000..9bcadc3880 --- /dev/null +++ b/ansible/docs/LAB05.md @@ -0,0 +1,532 @@ +# Lab 5 — Ansible Fundamentals +## 1. Architecture Overview + +### Ansible Version +```bash +ansible [core 2.16.3] +config file = /workspace/ansible.cfg +python version = 3.12.3 +``` + +### Target VM Information +**OS:** Ubuntu 24.04.3 LTS +**Kernel:** Linux 6.14.0-1018-aws x86_64 +**Python:** 3.12.3 (pre-installed) +**Provider:** AWS EC2 +**Instance Type:** t2.micro (Free Tier) +**Public IP:** 34.229.125.207 +**SSH User:** ubuntu + +### Ansible Architecture Diagram + +``` +┌─────────────────────────────────────────────────────┐ +│ Local Machine (Ansible Control Node) │ +├─────────────────────────────────────────────────────┤ +│ │ +│ ansible/ │ +│ ├── inventory/hosts.ini → aws-vm (34.229.125.207) │ +│ ├── ansible.cfg → Configuration │ +│ ├── playbooks/ │ +│ │ ├── provision.yml → common + docker roles │ +│ │ └── deploy.yml → app_deploy role │ +│ │ │ +│ └── roles/ │ +│ ├── common/ → Update apt, install pkgs │ +│ ├── docker/ → Install & configure │ +│ └── app_deploy/ → Pull image, run container │ +│ │ +└────────────┬────────────────────────────────────────┘ + │ SSH + Ansible + ↓ +┌─────────────────────────────────────────────────────┐ +│ AWS EC2 Ubuntu 24.04 (34.229.125.207) │ +├─────────────────────────────────────────────────────┤ +│ Common packages installed (curl, git, vim, etc) │ +│ Docker installed and running │ +│ python3-docker installed │ +│ devops-app container running on port 5000 │ +│ Health endpoint responding │ +└─────────────────────────────────────────────────────┘ +``` + +### Why Roles Instead of Monolithic Playbooks? + +**Benefits of Role-Based Architecture:** + +1. **Reusability** - Same role can be used across multiple playbooks and projects + - Example: `docker` role can provision any server needing Docker + - No code duplication across different playbooks + +2. **Maintainability** - Changes in one place affect all uses + - Update Docker installation in one role file + - All playbooks using that role automatically get the update + +3. **Organization** - Clear structure, easy to navigate and understand + - Each role has single responsibility (common, docker, app_deploy) + - Easier for new team members to find relevant code + +4. **Testing** - Can test roles independently + - Test `docker` role in isolation before using in playbooks + - Verify role functionality before deployment + +5. **Sharing** - Can publish to Ansible Galaxy for community use + - Professional standard for Ansible code organization + - Industry best practice +--- + +## 2. Roles Documentation + +### 2.1 Common Role + +**Purpose:** +Basic system setup that every server needs - updates package manager, installs essential tools, and configures system settings like timezone. + +**Key Variables (`roles/common/defaults/main.yml`):** +```yaml +common_packages: + - python3-pip + - curl + - git + - vim + - htop + - wget + - ca-certificates + - apt-transport-https + - gnupg + - lsb-release +``` + +**Handlers:** +None (no services to restart) + +**Dependencies:** +None + +--- + +### 2.2 Docker Role + +**Purpose:** +Install Docker engine and configure it for containerized applications. Ensures Docker daemon is running, users have permissions, and Python Docker modules are available for Ansible automation. + +**Key Variables (`roles/docker/defaults/main.yml`):** +```yaml +docker_version: "24.0" +docker_users: + - ubuntu +``` + +**Handlers (`roles/docker/handlers/main.yml`):** +```yaml +- name: restart docker + service: + name: docker + state: restarted + enabled: yes +``` + +**Dependencies:** +None (but typically runs after `common` role for proper ordering) + +--- + +### 2.3 App_Deploy Role + +**Purpose:** +Securely deploy containerized Python application using Docker Hub. Pulls images using encrypted credentials from Ansible Vault, manages container lifecycle, and verifies application health. + +**Key Variables (`roles/app_deploy/defaults/main.yml`):** +```yaml +app_name: devops-app +docker_image: devops-info-service +docker_image_tag: latest +app_port: 5000 +app_internal_port: 5000 +app_container_name: "{{ app_name }}" +restart_policy: unless-stopped +``` + +**Encrypted Variables (`group_vars/all.yml` via Vault):** +```yaml +dockerhub_username: sunflye +dockerhub_password: +``` + +**Handlers (`roles/app_deploy/handlers/main.yml`):** +```yaml +- name: restart app + community.docker.docker_container: + name: "{{ app_container_name }}" + image: "{{ docker_image }}:{{ docker_image_tag }}" + state: started + ports: + - "{{ app_port }}:{{ app_internal_port }}" + restart_policy: "{{ restart_policy }}" + env: + PORT: "{{ app_internal_port | string }}" + HOST: "0.0.0.0" + force_kill: yes +``` +**Dependencies:** Implicitly depends on Docker being installed (though not formally declared) + +--- + +## 3. Idempotency Demonstration + +### 3.1 First Provision Run (with changes) + +``` +root@1fde1d5f6de8:/workspace# ansible-playbook playbooks/provision.yml + +PLAY [Provision web servers] ********************************************************** + +TASK [Gathering Facts] **************************************************************** +ok: [aws-vm] + +TASK [common : Update apt cache] ****************************************************** +changed: [aws-vm] + +TASK [common : Install common packages] *********************************************** +changed: [aws-vm] + +TASK [common : Set timezone to UTC] *************************************************** +changed: [aws-vm] + +TASK [docker : Install Docker prerequisites] ****************************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] **************************************************** +changed: [aws-vm] + +TASK [docker : Add Docker repository] ************************************************* +changed: [aws-vm] + +TASK [docker : Install Docker packages] *********************************************** +changed: [aws-vm] + +TASK [docker : Enable Docker service] ************************************************* +ok: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] *************************************** +changed: [aws-vm] + +TASK [docker : Install python3-docker via apt (Ubuntu 24.04 fix)] ********************* +changed: [aws-vm] + +PLAY RECAP **************************************************************************** +aws-vm : ok=11 changed=9 unreachable=0 failed=0 +``` + +**Summary:** +- **ok=11** - Tasks that ran, no change needed +- **changed=9** - Tasks that made changes to reach desired state +- **Total changed:** 9/11 tasks made changes + +### 3.2 Second Provision Run (idempotency verification) + +``` +root@1fde1d5f6de8:/workspace# ansible-playbook playbooks/provision.yml + +PLAY [Provision web servers] ********************************************************** + +TASK [Gathering Facts] **************************************************************** +ok: [aws-vm] + +TASK [common : Update apt cache] ****************************************************** +ok: [aws-vm] + +TASK [common : Install common packages] *********************************************** +ok: [aws-vm] + +TASK [common : Set timezone to UTC] *************************************************** +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] ****************************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] **************************************************** +ok: [aws-vm] + +TASK [docker : Add Docker repository] ************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker packages] *********************************************** +ok: [aws-vm] + +TASK [docker : Enable Docker service] ************************************************* +ok: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] *************************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt (Ubuntu 24.04 fix)] ********************* +ok: [aws-vm] + +PLAY RECAP **************************************************************************** +aws-vm : ok=11 changed=0 unreachable=0 failed=0 +``` + +**Summary:** +- **ok=11** - All tasks ran, no changes needed +- **changed=0** - **CRITICAL: No tasks made changes!** +- **Result: IDEMPOTENT** + +### 3.3 Analysis: What Changed First Run? + +**Tasks that changed (9 total):** + +1. **Update apt cache** - Package list was outdated, needed refresh +2. **Install common packages** - Packages not installed yet +3. **Set timezone to UTC** - System was not in UTC (was local time) +4. **Add Docker GPG key** - Key not in trusted keyring yet +5. **Add Docker repository** - Repository not configured yet +6. **Install Docker packages** - Docker binaries not installed +7. **Add ubuntu user to docker group** - User not in group yet +8. **Install python3-docker via apt** - Package not installed yet + +**Tasks that didn't change (2 total):** + +1. **Gathering Facts** - Fact gathering (always ok) +2. **Install Docker prerequisites** - Dependencies already satisfied from apt update + +### 3.4 Why Nothing Changed Second Run? + +**Idempotency Explanation:** + +All tasks use **state-based modules** that check current state before making changes: + +```yaml +# Example from common role: +- name: Install common packages + apt: + name: "{{ common_packages }}" + state: present # ← Only installs if not present +``` + +**How it works:** + +1. **First run:** Package not installed → Install it → changed +2. **Second run:** Package already installed → Skip installation → ok (no change) + +**Key Idempotency Patterns Used:** + +| Module | Idempotent Parameter | Behavior | +|--------|---------------------|----------| +| `apt` | `state: present` | Only installs if not already installed | +| `service` | `state: started` | Only starts if not already running | +| `timezone` | Compare with current | Only changes if different | +| `user` | `append: yes` | Only adds group if not already member | +| `apt_key` | `state: present` | Only adds if not already trusted | +| `apt_repository` | `state: present` | Only adds if not already in sources | + +**Why This Matters:** + +- Safe to re-run playbooks without side effects +- Can recover from partial failures +- Detects configuration drift +- Convergence to desired state +- No accidental double installations + +--- + +## 4. Ansible Vault Usage + +### 4.1 Secure Credential Storage + +**Problem:** Cannot commit Docker Hub password to Git unencrypted. + +**Solution:** Ansible Vault encrypts sensitive data. + +**Implementation:** + +```bash +# Create encrypted file +ansible-vault create group_vars/all.yml + +# Enter password when prompted +dockerhub_username: sunflye +dockerhub_password: +app_name: devops-app +docker_image: sunflye/devops-info-service +docker_image_tag: latest +app_port: 5000 +app_container_name: devops-app +app_internal_port: 5000 +``` + +### 4.2 Vault File Encrypted +``` +$ANSIBLE_VAULT;1.1;AES256 +64626236626237363934303230333132306563653264633033616363386164313831313235383565 +3430323936633631343636353963346563383538663730630a333961373337373436363262616635 +36393432343435343833666537373139663139313038346663653737613737653961613363353131 +6664323739633332300a626437303134353231343735626261353461666538653033323737393564 +63643838393539396437383363666162653732303836616333346231323465633634303633333837 +37343637316464663731646536323233323834333733343366303233346565363362326430326165 +66326431646637316463653662636566346633333231666438336432303332633939323033656361 +35383466373366323863623830383236306331646439623961313035616530646237393732303233 +66333433333732396238323739643162396563373831636466383938613061383832363561613763 +39633463623739373366626362346633306261623764333337346361366165633630613536636537 +36663231326462613438653138316536653730333436663936326632383265336638646263303835 +33393737366533666236323239616636366663643533373634613330373632393634323737393331 +32313464376637333366666534363439313163323932313436646263666364363539333737316634 +63653939353361383733303733383433393966646139643836333834613764323861353431346164 +35626535616539323063333933383766363732633765306366333434343131303635306334353930 +35303661313864346338373138643932346438313662333462613235303662363238373663626233 +37396632613462623765636133356231386533376339386231383739383235323232643531613438 +6333386430316132383233663961333266346130633339396432 +``` + +### 4.3 Vault Password Management Strategy + +**Method Used:** `--ask-vault-pass` (prompt for password at runtime) + +**Advantages:** +- Password not stored in files +- Safe for CI/CD (can be passed via environment) +- No `.vault_pass` file to accidentally commit + +**Usage:** +```bash +ansible-playbook playbooks/deploy.yml --ask-vault-pass +``` + + +### 4.4 Why Ansible Vault is Important + +1. **Security** - Encrypts credentials, not readable in plaintext +2. **Collaboration** - Can commit encrypted file to Git safely +3. **Audit Trail** - Can track when secrets were last used +4. **Rotation** - Easy to rotate passwords (re-encrypt file) +5. **Compliance** - Meets security requirements for credential management +6. **Best Practice** - Industry standard for secret management in Ansible + +--- + +## 5. Deployment Verification + +### 5.1 Deployment Run + +Firstly, I had some errors during these stages, but then I fixed them, so this is the output of the third deployment run when it finally worked +``` +root@1fde1d5f6de8:/workspace# ansible-playbook playbooks/deploy.yml --ask-vault-pass +Vault password: + +PLAY [Deploy application] ************************************************************* + +TASK [Gathering Facts] **************************************************************** +ok: [aws-vm] + +TASK [app_deploy : Login to Docker Hub] *********************************************** +ok: [aws-vm] + +TASK [app_deploy : Pull Docker image] ************************************************* +ok: [aws-vm] + +TASK [app_deploy : Stop existing container (if running)] ****************************** +changed: [aws-vm] + +TASK [app_deploy : Remove old container (if exists)] ********************************** +changed: [aws-vm] + +TASK [app_deploy : Run application container] ***************************************** +changed: [aws-vm] + +TASK [app_deploy : Wait for application to be ready] ********************************** +ok: [aws-vm] + +TASK [app_deploy : Verify health endpoint] ******************************************** +ok: [aws-vm] + +TASK [app_deploy : Display health check result] *************************************** +ok: [aws-vm] => { + "msg": "✅ Application is healthy: healthy" +} + +RUNNING HANDLER [app_deploy : restart app] ******************************************** +ok: [aws-vm] + +PLAY RECAP **************************************************************************** +aws-vm : ok=10 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 + +``` + +**Summary:** +- All 10 tasks completed successfully +- 3 tasks made changes (stop, remove, run container) +- Health check passed +- Handler executed successfully + +### 5.2 Container Status Verification + +``` +root@1fde1d5f6de8:/workspace# ansible webservers -a "docker ps" --ask-vault-pass +Vault password: +aws-vm | CHANGED | rc=0 >> +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +afc9c0fb699a sunflye/devops-info-service:latest "python app.py" 28 minutes ago Up 28 minutes 0.0.0.0:5000->5000/tcp devops-app +``` + +### 5.3 Health Check Verification and Main Endpoint Verification + +``` +root@1fde1d5f6de8:/workspace# curl http://34.229.125.207:5000/ +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"}],"request":{"client_ip":"188.130.155.165","method":"GET","path":"/","user_agent":"curl/8.5.0"},"runtime":{"current_time":"2026-02-24T20:18:00.835698Z","timezone":"UTC","uptime_human":"0 hour, 29 minutes","uptime_seconds":1782},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":1,"hostname":"afc9c0fb699a","platform":"Linux","platform_version":"Linux-6.14.0-1018-aws-x86_64-with-glibc2.41","python_version":"3.13.12"}} +root@1fde1d5f6de8:/workspace# curl http://34.229.125.207:5000/health +{"status":"healthy","timestamp":"2026-02-24T20:18:03.445124Z","uptime_seconds":1784} +root@1fde1d5f6de8:/workspace# +``` + +### 5.4 Handler Execution + +**Handler triggered during deployment:** +``` +RUNNING HANDLER [app_deploy : restart app] ************ +ok: [aws-vm] +``` +## 6. Key Decisions + +### 6.1 Why use roles instead of plain playbooks? + +Roles provide code reusability and maintainability at scale. Rather than writing all tasks in one playbook, roles organize code into logical units that can be applied independently. This allows the same role (e.g., Docker installation) to be used across multiple playbooks or projects without duplication, making infrastructure-as-code more modular and professional. + +--- + +### 6.2 How do roles improve reusability? + +Each role has a single responsibility (common system setup, Docker installation, app deployment). This separation means the `docker` role can be used on any server type - database servers, app servers, monitoring systems - without modification. Variables in `defaults/` allow customization without changing role logic, making roles portable across projects and organizations. + +--- + +### 6.3 What makes a task idempotent? + +Idempotent tasks check current state before making changes. The `apt` module checks if a package is already installed before installing, so running it twice produces the same result (package installed). This differs from shell commands which execute every time, potentially causing unintended consequences on repeated runs. + +--- + +### 6.4 How do handlers improve efficiency? + +Handlers are event-driven and only execute when notified by changed tasks. If Docker configuration changes, the handler restarts the service. But if Docker is already installed and unchanged, the handler doesn't run unnecessarily. This improves efficiency by avoiding redundant service restarts and reducing deployment time. + +--- + +### 6.5 Why is Ansible Vault necessary? + +Vault prevents accidental exposure of secrets (passwords, API keys, tokens) in Git repositories and logs. Docker Hub credentials must not be stored in plaintext in version control. Vault encrypts sensitive data at rest while keeping it readable at runtime through password-protected decryption, following security best practices for credential management. + +--- + +## 7. Challenges Encountered + +### Challenge 1: pip3 on Ubuntu 24.04 + +**Problem:** `pip install docker` failed with "externally-managed-environment" error. + +**Solution:** Used `apt install python3-docker` instead of pip, respecting Ubuntu 24.04's policy of managing Python packages system-wide. + +### Challenge 2: Docker Container Environment Variables + +**Problem:** Environment variables (PORT, HOST) not recognized as strings in Ansible. + +**Solution:** Applied Jinja2 filter `| string` to convert integer to string: `PORT: "{{ app_internal_port | string }}"` diff --git a/ansible/docs/LAB06.md b/ansible/docs/LAB06.md new file mode 100644 index 0000000000..5b4c2078d1 --- /dev/null +++ b/ansible/docs/LAB06.md @@ -0,0 +1,1205 @@ +# Lab 6 — Advanced Ansible & CI/CD + +## Overview + +**What I Accomplished:** +- Refactored Ansible roles with blocks and tags for better control +- Upgraded application deployment from `docker run` to Docker Compose v2 +- Implemented safe wipe logic with double-safety gates (variable + tag) +- Automated deployment pipeline with GitHub Actions CI/CD +- Full idempotency and error handling throughout + +**Technologies Used:** +- **Ansible 2.20.3** with community.docker collection +- **Docker Compose v2** for declarative deployments +- **GitHub Actions** for automated CI/CD +- **Jinja2** templating for dynamic configuration +- **Ansible Vault** for secure credential management + +**Architecture:** +``` +Code Push → GitHub Actions + ↓ +ansible-lint (syntax check) + ↓ +SSH to target VM (using GitHub Secrets) + ↓ +ansible-playbook deploy.yml (with Vault decryption) + ↓ +docker-compose up (idempotent) + ↓ +Health check verification + ↓ +✅ Deployment complete +``` + +## Task 1: Blocks & Tags Refactoring + +### Implementation + +**File:** `roles/docker/tasks/main.yml` +**File:** `roles/common/tasks/main.yml` + +Both roles refactored to use blocks with: +- **`block`** - Group related tasks +- **`rescue`** - Handle failures (e.g., retry apt update) +- **`always`** - Ensure logging even if tasks fail +- **`tags`** - Enable selective execution + +**Block Strategy:** +```yaml +- name: Docker installation and setup + block: + # All installation tasks here + rescue: + # Retry logic + always: + # Logging and cleanup + tags: + - docker_install +``` + +### Tag Strategy + +**Available Tags:** +- `docker` - Entire Docker role +- `docker_install` - Installation tasks only +- `docker_config` - Configuration tasks only +- `packages` - Package installation +- `system` - System configuration + +### Evidence: Selective Execution + +**Scenario 1: Run only Docker installation** +``` + root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/provision.yml --tags "docker" --ask-vault-pass +Vault password: + +PLAY [Provision web servers] ****************************************************************** + +TASK [Gathering Facts] ************************************************************************ +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] ************************************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ************************************************************ +ok: [aws-vm] + +TASK [docker : Add Docker repository] ********************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker packages] ******************************************************* +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ********************************** +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ******************************************** +changed: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] *********************************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ************************************************ +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] ************************************** +changed: [aws-vm] + +PLAY RECAP ************************************************************************************ +aws-vm : ok=10 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + + +**Scenario 2: List all available tags** + +```bash +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml --list-tags +playbook: playbooks/deploy.yml + + play + TASK TAGS: [app_deploy, compose, docker, docker_install, web_app, web_app_wipe] +``` +**Result:** All tags visible and can be used for selective execution + + +**Scenario 3: Rescue block error handling** + +When apt GPG key addition fails, rescue block retries with fix-missing: + +```bash +TASK [docker : Retry apt update with fix-missing] **** +changed: [aws-vm] + +TASK [docker : Retry Docker installation] **** +changed: [aws-vm] +``` + +**Result:** Error handling gracefully retries without playbook failure + +**Scenario 4: Skip common role** +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/provision.yml --skip-tags "common" --ask-vault-pass +Vault password: + +PLAY [Provision web servers] ****************************************************************** + +TASK [Gathering Facts] ************************************************************************ +ok: [aws-vm] + +TASK [common : Update apt cache] ************************************************************** +changed: [aws-vm] + +TASK [common : Install common packages] ******************************************************* +ok: [aws-vm] + +TASK [common : Log package installation completion] ******************************************* +changed: [aws-vm] + +TASK [docker : Install Docker prerequisites] ************************************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ************************************************************ +ok: [aws-vm] + +TASK [docker : Add Docker repository] ********************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker packages] ******************************************************* +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ********************************** +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ******************************************** +changed: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] *********************************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ************************************************ +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] ************************************** +changed: [aws-vm] + +PLAY RECAP ************************************************************************************ +aws-vm : ok=13 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +**Scenario 5: Install packages only across all roles** +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/provision.yml --tags "packages" --ask-vault-pass +Vault password: + +PLAY [Provision web servers] ****************************************************************** + +TASK [Gathering Facts] ************************************************************************ +ok: [aws-vm] + +TASK [common : Update apt cache] ************************************************************** +ok: [aws-vm] + +TASK [common : Install common packages] ******************************************************* +ok: [aws-vm] + +TASK [common : Log package installation completion] ******************************************* +changed: [aws-vm] + +PLAY RECAP ************************************************************************************ +aws-vm : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +**Scenario 6: Check mode to see what would run** + +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/provision.yml --tags "docker" --check --ask-vault-pass +Vault password: + +PLAY [Provision web servers] ****************************************************************** + +TASK [Gathering Facts] ************************************************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker packages] ******************************************************* +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ********************************** +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ******************************************** +changed: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] *********************************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ************************************************ +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] ************************************** +changed: [aws-vm] + +PLAY RECAP ************************************************************************************ +aws-vm : ok=10 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +**Scenario 7: Run only docker installation tasks** +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/provision.yml --tags "docker_install" --ask-vault-pass +Vault password: + +PLAY [Provision web servers] ****************************************************************** + +TASK [Gathering Facts] ************************************************************************ +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] ************************************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ************************************************************ +ok: [aws-vm] + +TASK [docker : Add Docker repository] ********************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker packages] ******************************************************* +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ********************************** +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ******************************************** +changed: [aws-vm] + +PLAY RECAP ************************************************************************************ +aws-vm : ok=7 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +## Task 2: Docker Compose Migration + +### Implementation + +**File:** `roles/web_app/tasks/main.yml` + +Replaced individual `docker run` with Docker Compose v2: + +```yaml +- name: Deploy with Docker Compose + community.docker.docker_compose_v2: + project_src: "{{ web_app_compose_project_dir }}" + state: present + pull: missing + recreate: auto +``` + +### Docker Compose Template + +**File:** `roles/web_app/templates/docker-compose.yml.j2` + +```yaml +version: '3.8' + +services: + {{ web_app_name }}: + image: {{ web_app_docker_image }}:{{ web_app_docker_tag }} + container_name: {{ web_app_name }} + ports: + - "{{ web_app_port }}:{{ web_app_internal_port }}" + environment: + PORT: "{{ web_app_internal_port }}" + HOST: "0.0.0.0" + restart: {{ web_app_restart_policy }} + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:{{ web_app_internal_port }}/health"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 10s +``` + +**Variables Used:** +- `web_app_name` - Container and service name +- `web_app_docker_image` - Docker Hub image repository +- `web_app_docker_tag` - Image version tag +- `web_app_port` - Host port (5000) +- `web_app_internal_port` - Container port (5000) +- `web_app_restart_policy` - Restart behavior (unless-stopped) + +### Role Dependencies + +**File:** `roles/web_app/meta/main.yml` + +```yaml +--- +dependencies: + - role: docker +``` + +**Purpose:** Ensures Docker is installed before web_app deployment runs + +### Evidence: Docker Compose Deployment Success + +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml --ask-vault-pass +Vault password: + +PLAY [Deploy application] ****************************************************** + +TASK [Gathering Facts] ********************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] *********************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ********************************************* +ok: [aws-vm] + +TASK [docker : Add Docker repository] ****************************************** +ok: [aws-vm] + +TASK [docker : Install Docker packages] **************************************** +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ******************* +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ***************************** +ok: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] ******************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ********************************* +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] *********************** +ok: [aws-vm] + +TASK [web_app : Stop and remove old containers] ******************************** +changed: [aws-vm] + +TASK [web_app : Create application directory] ********************************** +ok: [aws-vm] + +TASK [web_app : Template docker-compose.yml] *********************************** +ok: [aws-vm] + +TASK [web_app : Deploy with Docker Compose] ************************************ +changed: [aws-vm] + +TASK [web_app : Wait for application to be ready] ****************************** +ok: [aws-vm] +changed: [aws-vm] + +TASK [web_app : Wait for application to be ready] ****************************** +ok: [aws-vm] + +TASK [web_app : Wait for application to be ready] ****************************** +ok: [aws-vm] +********** +ok: [aws-vm] +ok: [aws-vm] + +TASK [web_app : Verify health endpoint] **************************************** +ok: [aws-vm] + +TASK [web_app : Display health check result] *********************************** +ok: [aws-vm] => { + "msg": "✅ Application is healthy: healthy" +} + +TASK [web_app : Log deployment completion] ************************************* +ok: [aws-vm] + +PLAY RECAP ********************************************************************* +aws-vm : ok=18 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` +### Evidence: Idempotency (Second Run) + +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml --ask-vault-pass +Vault password: + +PLAY [Deploy application] ****************************************************** + +TASK [Gathering Facts] ********************************************************* + +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] *********************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ********************************************* +ok: [aws-vm] + +TASK [docker : Add Docker repository] ****************************************** +ok: [aws-vm] + +TASK [docker : Install Docker packages] **************************************** +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ******************* +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ***************************** +ok: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] ******************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ********************************* +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] *********************** +ok: [aws-vm] + +TASK [web_app : Stop and remove old containers] ******************************** +ok: [aws-vm] + +TASK [web_app : Create application directory] ********************************** +ok: [aws-vm] + +TASK [web_app : Template docker-compose.yml] *********************************** +ok: [aws-vm] + +TASK [web_app : Deploy with Docker Compose] ************************************ +ok: [aws-vm] + +TASK [web_app : Wait for application to be ready] ****************************** +ok: [aws-vm] + +TASK [web_app : Verify health endpoint] **************************************** +ok: [aws-vm] + +TASK [web_app : Display health check result] *********************************** +ok: [aws-vm] => { + "msg": "✅ Application is healthy: healthy" +} + +TASK [web_app : Log deployment completion] ************************************* +ok: [aws-vm] + +PLAY RECAP ********************************************************************* +aws-vm : ok=18 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` +### Evidence: Application Accessible and Contents of templated docker-compose.yml + +``` +ubuntu@ip-172-31-28-215:~$ ls -la /opt/devops-app/ +total 12 +drwxr-xr-x 2 root root 4096 Mar 5 10:13 . +drwxr-xr-x 4 root root 4096 Mar 5 10:12 .. +-rw-r--r-- 1 root root 396 Mar 5 10:12 docker-compose.yml +ubuntu@ip-172-31-28-215:~$ cat /opt/devops-app/docker-compose.yml +version: '3.8' + +services: + devops-app: + image: sunflye/devops-info-service:latest + container_name: devops-app + ports: + - "5000:5000" + environment: + PORT: "5000" + HOST: "0.0.0.0" + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:5000/health"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 10subuntu@ip-172-31-28-215:~$ docker ps +CONTAINER ID IMAGE COMMAND +CREATED STATUS PORTS + NAMES +87f530789cca sunflye/devops-info-service:latest "python app.py" 6 minutes ago Up 6 minutes (unhealthy) 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp devops-app +ubuntu@ip-172-31-28-215:~$ curl http://localhost:5000 +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"}],"request":{"client_ip":"172.18.0.1","method":"GET","path":"/","user_agent":"curl/8.5.0"},"runtime":{"current_time":"2026-03-05T10:49:14.169009Z","timezone":"UTC","uptime_human":"0 hour, 7 minutes","uptime_seconds":450},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":1,"hostname":"87f530789cca","platform":"Linux","platform_version":"Linux-6.14.0-1018-aws-x86_64-with-glibc2.41","python_version":"3.13.12"}} +ubuntu@ip-172-31-28-215:~$ curl http://localhost:5000/health +{"status":"healthy","timestamp":"2026-03-05T10:49:25.240764Z","uptime_seconds":461} +ubuntu@ip-172-31-28-215:~$ +``` + +## Task 3: Wipe Logic Implementation + +### Implementation + +**File:** `roles/web_app/tasks/wipe.yml` + +```yaml +--- +- name: Wipe web application + when: web_app_wipe | bool + tags: + - web_app_wipe + block: + - name: Stop and remove containers with Docker Compose + community.docker.docker_compose_v2: + project_src: "{{ web_app_compose_project_dir }}" + state: absent + failed_when: false + + - name: Remove docker-compose.yml file + ansible.builtin.file: + path: "{{ web_app_compose_project_dir }}/docker-compose.yml" + state: absent + failed_when: false + + - name: Remove application directory + ansible.builtin.file: + path: "{{ web_app_compose_project_dir }}" + state: absent + failed_when: false + + - name: Log wipe completion + ansible.builtin.debug: + msg: "✅ Application {{ web_app_name }} wiped successfully" +``` + +**File:** `roles/web_app/defaults/main.yml` + +```yaml +# Wipe Logic Control +web_app_wipe: false + +# Documentation: +# Set to true to remove application completely +# Wipe only: ansible-playbook deploy.yml -e "web_app_wipe=true" --tags web_app_wipe +# Clean install: ansible-playbook deploy.yml -e "web_app_wipe=true" +``` +### Double Safety Mechanism + +``` +Requirement 1: Variable Gate + web_app_wipe: false (default) + +Requirement 2: Tag Gate + --tags web_app_wipe (must specify) + +Both required for execution +``` +### Evidence: Scenario 1 (Normal Deployment - Wipe Skipped) + +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml --ask-vault-pass +Vault password: + +PLAY [Deploy application] ****************************************************** + +TASK [Gathering Facts] ********************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] *********************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ********************************************* +ok: [aws-vm] + +TASK [docker : Add Docker repository] ****************************************** +ok: [aws-vm] + +TASK [docker : Install Docker packages] **************************************** +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ******************* +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ***************************** +ok: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] ******************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ********************************* +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] *********************** +ok: [aws-vm] + +TASK [web_app : Include wipe tasks] ******************************************** +included: /workspace/ansible/roles/web_app/tasks/wipe.yml for aws-vm + +TASK [web_app : Stop and remove containers with Docker Compose] **************** +skipping: [aws-vm] + +TASK [web_app : Remove docker-compose.yml file] ******************************** +skipping: [aws-vm] + +TASK [web_app : Remove application directory] ********************************** +skipping: [aws-vm] + +TASK [web_app : Log wipe completion] ******************************************* +skipping: [aws-vm] + +TASK [web_app : Remove old container (idempotent)] ***************************** +changed: [aws-vm] + +TASK [web_app : Create application directory] ********************************** +ok: [aws-vm] + +TASK [web_app : Template docker-compose.yml] *********************************** +ok: [aws-vm] + +TASK [web_app : Deploy with Docker Compose] ************************************ +changed: [aws-vm] + +TASK [web_app : Wait for application to be ready] ****************************** +ok: [aws-vm] + +TASK [web_app : Verify health endpoint] **************************************** +ok: [aws-vm] + +TASK [web_app : Display health check result] *********************************** +ok: [aws-vm] => { + "msg": "✅ Application is healthy: healthy" +} + +TASK [web_app : Log deployment completion] ************************************* +ok: [aws-vm] + +PLAY RECAP ********************************************************************* +aws-vm : ok=19 changed=2 unreachable=0 failed=0 skipped=4 rescued=0 ignored=0 +``` +### Evidence: Scenario 2 (Wipe Only) + +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml -e "web_app_wipe=true" --tags web_app_wipe --ask-vault-pass +Vault password: + +PLAY [Deploy application] ****************************************************** + +TASK [Gathering Facts] ********************************************************* +ok: [aws-vm] + +TASK [web_app : Include wipe tasks] ******************************************** +included: /workspace/ansible/roles/web_app/tasks/wipe.yml for aws-vm + +TASK [web_app : Stop and remove containers with Docker Compose] **************** +changed: [aws-vm] + +TASK [web_app : Remove docker-compose.yml file] ******************************** +changed: [aws-vm] + +TASK [web_app : Remove application directory] ********************************** +changed: [aws-vm] + +TASK [web_app : Log wipe completion] ******************************************* +ok: [aws-vm] => { + "msg": "✅ Application devops-app wiped successfully" +} + +PLAY RECAP ********************************************************************* +aws-vm : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` +**Verification on VM:** +``` +ubuntu@ip-172-31-28-215:~$ docker ps +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +ubuntu@ip-172-31-28-215:~$ ls /opt +containerd +ubuntu@ip-172-31-28-215:~$ +``` + +### Evidence: Scenario 3 (Clean Reinstall - Wipe → Deploy) + +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml -e "web_app_wipe=true" --ask-vault-pass +Vault password: + +PLAY [Deploy application] ****************************************************** + +TASK [Gathering Facts] ********************************************************* +ok: [aws-vm] + +TASK [docker : Install Docker prerequisites] *********************************** +ok: [aws-vm] + +TASK [docker : Add Docker GPG key] ********************************************* +ok: [aws-vm] + +TASK [docker : Add Docker repository] ****************************************** +ok: [aws-vm] + +TASK [docker : Install Docker packages] **************************************** +ok: [aws-vm] + +TASK [docker : Ensure Docker service is started and enabled] ******************* +ok: [aws-vm] + +TASK [docker : Log Docker installation completion] ***************************** +ok: [aws-vm] + +TASK [docker : Add ubuntu user to docker group] ******************************** +ok: [aws-vm] + +TASK [docker : Install python3-docker via apt] ********************************* +ok: [aws-vm] + +TASK [docker : Log Docker user configuration completion] *********************** +ok: [aws-vm] + +TASK [web_app : Include wipe tasks] ******************************************** +included: /workspace/ansible/roles/web_app/tasks/wipe.yml for aws-vm + +TASK [web_app : Stop and remove containers with Docker Compose] **************** +[ERROR]: Task failed: Module failed: "/opt/devops-app" is not a directory +Origin: /workspace/ansible/roles/web_app/tasks/wipe.yml:4:7 + +2 - name: Wipe web application +3 block: +4 - name: Stop and remove containers with Docker Compose + ^ column 7 + +fatal: [aws-vm]: FAILED! => {"changed": false, "msg": "\"/opt/devops-app\" is not a directory"} +...ignoring + +TASK [web_app : Remove docker-compose.yml file] ******************************** +ok: [aws-vm] + +TASK [web_app : Remove application directory] ********************************** +ok: [aws-vm] + +TASK [web_app : Log wipe completion] ******************************************* +ok: [aws-vm] => { + "msg": "✅ Application devops-app wiped successfully" +} + +TASK [web_app : Remove old container (idempotent)] ***************************** +ok: [aws-vm] + +TASK [web_app : Create application directory] ********************************** +changed: [aws-vm] + +TASK [web_app : Template docker-compose.yml] *********************************** +changed: [aws-vm] + +TASK [web_app : Deploy with Docker Compose] ************************************ +changed: [aws-vm] + +TASK [web_app : Wait for application to be ready] ****************************** +ok: [aws-vm] + +TASK [web_app : Verify health endpoint] **************************************** +ok: [aws-vm] + +TASK [web_app : Display health check result] *********************************** +ok: [aws-vm] => { + "msg": "✅ Application is healthy: healthy" +} + +TASK [web_app : Log deployment completion] ************************************* +ok: [aws-vm] + +PLAY RECAP ********************************************************************* +aws-vm : ok=23 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1 + +``` + +``` +ubuntu@ip-172-31-28-215:~$ docker ps +CONTAINER ID IMAGE COMMAND +CREATED STATUS PORTS + NAMES +913fcc423fb1 sunflye/devops-info-service:latest "python app.py" 54 seconds ago Up 54 seconds (health: starting) 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp devops-app +``` + +### Evidence: Scenario 4a (Safety Check - Tag Without Variable) +``` +root@eb4c97f4930a:/workspace/ansible# ansible-playbook playbooks/deploy.yml --tags web_app_wipe --ask-vault-pass +Vault password: + +PLAY [Deploy application] ****************************************************** + +TASK [Gathering Facts] ********************************************************* +ok: [aws-vm] + +TASK [web_app : Include wipe tasks] ******************************************** +included: /workspace/ansible/roles/web_app/tasks/wipe.yml for aws-vm + +TASK [web_app : Stop and remove containers with Docker Compose] **************** +skipping: [aws-vm] + +TASK [web_app : Remove docker-compose.yml file] ******************************** +skipping: [aws-vm] + +TASK [web_app : Remove application directory] ********************************** +skipping: [aws-vm] + +TASK [web_app : Log wipe completion] ******************************************* +skipping: [aws-vm] + +PLAY RECAP ********************************************************************* +aws-vm : ok=2 changed=0 unreachable=0 failed=0 skipped=4 rescued=0 ignored=0 +``` +### Screenshot of application running after clean reinstall +![task3](/ansible/docs/screenshots/task3_lab6.png) + +### Research Questions + +**Q1: Why use both variable AND tag? (Double safety mechanism)** + +**A:** Using both creates two independent gates that must both be satisfied: +1. **Variable gate** (`web_app_wipe: false`) - Default prevents accidental wipe +2. **Tag gate** (`--tags web_app_wipe`) - Requires explicit user intention + +This double-gating prevents common mistakes: +- If user runs `ansible-playbook deploy.yml --tags web_app_wipe` → Wipe skipped (variable=false) +- If user runs `ansible-playbook deploy.yml -e "web_app_wipe=true"` → Wipe skipped (tag not specified) +- Only `ansible-playbook deploy.yml -e "web_app_wipe=true" --tags web_app_wipe` → Executes wipe + +Similar to "sudo" requiring both `sudo` command AND password - redundant safety is better! + +--- + +**Q2: What's the difference between `never` tag and this approach?** + +**A:** +- **`never` tag** (Ansible special): + - Always skipped unless `--tags never` specified + - Can't be used for other purposes + - All-or-nothing approach + +- **Our approach** (variable + tag): + - Variable (`web_app_wipe`) controls behavior + - Tag (`web_app_wipe`) can be reused for other purposes + - More flexible: tag can filter other tasks too + - Better for infrastructure where you might want to wipe and later deploy + +Example: `--tags web_app_wipe` could filter logs, validation tasks, etc. + +--- + +**Q3: Why must wipe logic come BEFORE deployment in main.yml? (Clean reinstall scenario)** + +**A:** Ordering matters for the clean reinstall use case: + +``` +Execution order: +1. Wipe tasks run FIRST + ├─ Stop containers + ├─ Remove files + └─ Remove directory +2. Deployment tasks run SECOND + ├─ Create directory + ├─ Template config + └─ Start containers +``` + +If wipe was AFTER deployment: +- Old containers still running while new ones start +- Resource conflicts possible +- Not truly "clean" +- Could have version mismatches + +If wipe BEFORE deployment: +- Old installation completely removed first +- Fresh start guaranteed +- Clean slate for new version +- Safe to change Docker tags, configs, etc. + +--- + +**Q4: When would you want clean reinstallation vs. rolling update?** + +**A:** +| Scenario | Strategy | Reason | +|----------|----------|--------| +| Production, live traffic | Rolling update (default) | Zero downtime | +| Major version bump | Clean reinstall (wipe=true) | Config might be incompatible | +| Security patch | Rolling update | Fast, minimal downtime | +| Dev/Test environment | Clean reinstall | Fresh state, isolation | +| Upgrade base image OS | Clean reinstall | Kernel updates, system changes | +| Simple app update | Rolling update | Fastest, safest | +| Rollback scenario | Clean reinstall then redeploy | Cleaner than trying to fix | + +**Default behavior (rolling update)** is safest for production. +**Clean reinstall** useful for testing, major upgrades, troubleshooting. + +--- + +**Q5: How would you extend this to wipe Docker images and volumes too?** + +**A:** Add to `wipe.yml`: + +```yaml +- name: Remove Docker images (optional) + community.docker.docker_image: + name: "{{ web_app_docker_image }}:{{ web_app_docker_tag }}" + state: absent + failed_when: false + +- name: Remove Docker volumes (optional) + community.docker.docker_volume: + name: "{{ web_app_compose_project_dir | basename }}_data" + state: absent + failed_when: false + +- name: Remove Docker networks (optional) + community.docker.docker_network: + name: "{{ web_app_compose_project_dir | basename }}_default" + state: absent + failed_when: false +``` + +**Why useful:** +- Removes dangling images (saves disk space) +- Cleans unused volumes (data cleanup) +- Truly "factory reset" before upgrade +- Useful for environments with disk constraints + +--- + +## Task 4: CI/CD with GitHub Actions + +**Repository Settings → Secrets and variables → Actions** + +Required secrets: +1. `ANSIBLE_VAULT_PASSWORD` - Vault password +2. `SSH_PRIVATE_KEY` - SSH private key (full content) +3. `VM_HOST` - Target VM IP (54.90.150.210) +4. `VM_USER` - SSH username (ubuntu) + +### Screenshot of successful workflow run +![run](./screenshots/Screenshot%20of%20successful%20workflow%20run.png) + +### Output logs showing ansible-lint passing +![lint](./screenshots/linting.png) + +### Output logs showing ansible-playbook execution +![playbook](./screenshots/playbook.png) + +### Verification step output showing app responding +![verify](./screenshots/verify.png) + +### Status badge in README showing passing +`ansible/README.md` +![badge](./screenshots/badge.png) + +### Research Questions + +**Q1: What are the security implications of storing SSH keys in GitHub Secrets?** + +**A:** +- **Pros:** + - GitHub encrypts secrets at rest (AES-256) + - Only decrypted in secure CI/CD context + - Not visible in logs (unless explicitly echoed) + - Audit trail of access + +- **Cons & Mitigations:** + - Keys stored in plaintext during workflow runtime + - Mitigation: Use temporary files, delete immediately + - SSH key compromise = VM access + - Mitigation: Rotate keys regularly, use deploy keys with limited scope + - GitHub compromise = all secrets exposed + - Mitigation: Use separate service accounts, not prod credentials + +**Best Practices:** +```yaml +# ✅ GOOD: Write to temp file, use, delete +- name: Setup SSH + run: | + echo "${{ secrets.SSH_PRIVATE_KEY }}" > /tmp/id_rsa + chmod 600 /tmp/id_rsa + # Use it + rm /tmp/id_rsa # Delete immediately + +# ❌ BAD: Echo secret to logs +- run: echo ${{ secrets.SSH_PRIVATE_KEY }} +``` + +--- + +**Q2: How would you implement a staging → production deployment pipeline?** + +**A:** + +```yaml +jobs: + lint: + runs-on: ubuntu-latest + steps: + # ... linting + + deploy-staging: + name: Deploy to Staging + needs: lint + if: github.ref == 'refs/heads/develop' + runs-on: ubuntu-latest + steps: + - name: Deploy with Ansible to Staging + run: | + cd ansible + ansible-playbook playbooks/deploy.yml \ + -i inventory/staging.ini \ + --vault-password-file /tmp/vault_pass + test-staging: + name: Test Staging Deployment + needs: deploy-staging + runs-on: ubuntu-latest + steps: + - name: Run integration tests + run: | + # Test against staging VM + curl -f http://${{ secrets.STAGING_HOST }}/health + + approval: + name: Manual Approval + needs: test-staging + runs-on: ubuntu-latest + environment: production # Requires manual approval + steps: + - name: Approved by human + run: echo "Production deployment approved" + deploy-production: + name: Deploy to Production + needs: approval + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + steps: + - name: Deploy with Ansible to Production + run: | + cd ansible + ansible-playbook playbooks/deploy.yml \ + -i inventory/production.ini \ + --vault-password-file /tmp/vault_pass +``` +**Flow:** +``` +Code push to develop + ↓ +Lint, Deploy to Staging, Test + ↓ +Manual approval (GitHub Environments) + ↓ +Merge to main (or manual trigger) + ↓ +Deploy to Production +``` + +--- + +**Q3: What would you add to make rollbacks possible?** + +**A:** + +```yaml +# 1. Version Docker images with git tags +- name: Build and push with version tag + docker: + image: "{{ registry }}/{{ app_name }}:{{ github.sha | truncate(7) }}" + # Also push as: {{ version_tag }} + +# 2. Store deployment history +- name: Log deployment + lineinfile: + path: /opt/deployments.log + line: "{{ ansible_date_time.iso8601 }} - Version: {{ app_version }} - SHA: {{ github.sha }}" + +# 3. Create rollback playbook +- name: Rollback to previous version + community.docker.docker_compose_v2: + project_src: "{{ compose_project_dir }}" + state: present + vars: + app_version: "{{ previous_version }}" + +# 4. GitHub workflow for rollback +- name: Trigger manual rollback + workflow_dispatch: + inputs: + version: + description: 'Version to rollback to' + required: true + type: choice + options: + - v1.0.0 + - v1.1.0 + - v1.2.0 +``` + +**Usage:** +```bash +# Manual rollback via GitHub UI or CLI +gh workflow run rollback.yml -f version=v1.0.0 + +# Or via Ansible +ansible-playbook playbooks/rollback.yml \ + -e "rollback_version=v1.0.0" +``` +--- + +**Q4: How does self-hosted runner improve security compared to GitHub-hosted?** + +**A:** + +| Aspect | GitHub-hosted | Self-hosted | +|--------|---------------|------------| +| **Isolation** | Ephemeral VM, clean state | Your VM, persistent | +| **Network Access** | Limited, sandboxed | Direct network access to VPC | +| **SSH Key Storage** | GitHub servers | Your servers | +| **Cost** | Pay per minute | Your infrastructure | +| **Security** | GitHub responsibility | Your responsibility | +| **Speed** | Network latency | Direct connection | + +**Self-hosted Security Advantages:** +- Direct access to private VMs (no SSH over internet) +- Credentials never leave your network +- Can use AWS IAM roles instead of keys +- Audit logs on your systems +- Network segmentation with security groups + +**Self-hosted Setup:** +```bash +# On your VM +mkdir -p ~/actions-runner +cd ~/actions-runner +curl -o actions-runner-linux-x64-2.x.x.tar.gz https://github.com/actions/runner/releases/... +tar xzf ./actions-runner-linux-x64-2.x.x.tar.gz +./config.sh --url https://github.com/your-org/your-repo --token YOUR_TOKEN +./run.sh +``` + +**Better Practice:** Use both +- GitHub-hosted for linting (no secrets) +- Self-hosted for deployment (with secrets) + +--- + +## Testing Results Summary + +### All Test Scenarios Passed + +| Scenario | Command | Result | +|----------|---------|--------| +| Normal Deploy | `ansible-playbook deploy.yml` | App deployed, wipe skipped | +| Wipe Only | `-e "web_app_wipe=true" --tags web_app_wipe` | App removed completely | +| Clean Reinstall | `-e "web_app_wipe=true"` | Old removed, new deployed | +| Safety Check (tag without var) | `--tags web_app_wipe` | Wipe skipped (safe) | +| Idempotency | Run twice | Second run: changed=0 | +| CI/CD Pipeline | GitHub Actions workflow | Lint + Deploy successful | + +## Challenges & Solutions + +### Challenge 1: Ansible-lint FQCN violations +**Problem:** Modules like `apt`, `copy` flagged as not using fully qualified names +**Solution:** Converted all to `ansible.builtin.apt`, `ansible.builtin.copy`, etc. + +### Challenge 2: Vault password in CI/CD +**Problem:** Can't use `--ask-vault-pass` in GitHub Actions (no interactive input) +**Solution:** Pass vault password via GitHub Secret to temp file, delete after use + +### Challenge 3: SSH key in GitHub Secrets +**Problem:** Private key exposure during workflow +**Solution:** Write to temp file with `chmod 600`, delete immediately after playbook runs + +### Challenge 4: Docker Compose version warning +**Problem:** `version: '3.8'` deprecated in Docker Compose v2 +**Solution:** Warning acceptable (doesn't affect functionality), can be removed if needed + +### Challenge 5: Path filters in workflow +**Problem:** Workflow should skip on doc changes +**Solution:** Added `!ansible/docs/**` to path filter to exclude documentation + +--- \ No newline at end of file diff --git a/ansible/docs/screenshots/Screenshot of successful workflow run.png b/ansible/docs/screenshots/Screenshot of successful workflow run.png new file mode 100644 index 0000000000..522eef3b04 Binary files /dev/null and b/ansible/docs/screenshots/Screenshot of successful workflow run.png differ diff --git a/ansible/docs/screenshots/badge.png b/ansible/docs/screenshots/badge.png new file mode 100644 index 0000000000..081b8c9f8d Binary files /dev/null and b/ansible/docs/screenshots/badge.png differ diff --git a/ansible/docs/screenshots/linting.png b/ansible/docs/screenshots/linting.png new file mode 100644 index 0000000000..358b733232 Binary files /dev/null and b/ansible/docs/screenshots/linting.png differ diff --git a/ansible/docs/screenshots/playbook.png b/ansible/docs/screenshots/playbook.png new file mode 100644 index 0000000000..8f153710c5 Binary files /dev/null and b/ansible/docs/screenshots/playbook.png differ diff --git a/ansible/docs/screenshots/task3_lab6.png b/ansible/docs/screenshots/task3_lab6.png new file mode 100644 index 0000000000..630afaedad Binary files /dev/null and b/ansible/docs/screenshots/task3_lab6.png differ diff --git a/ansible/docs/screenshots/verify.png b/ansible/docs/screenshots/verify.png new file mode 100644 index 0000000000..896ccaa0bf Binary files /dev/null and b/ansible/docs/screenshots/verify.png differ diff --git a/ansible/group_vars/all.yml b/ansible/group_vars/all.yml new file mode 100644 index 0000000000..e95c40bdbb --- /dev/null +++ b/ansible/group_vars/all.yml @@ -0,0 +1,19 @@ +$ANSIBLE_VAULT;1.1;AES256 +64626236626237363934303230333132306563653264633033616363386164313831313235383565 +3430323936633631343636353963346563383538663730630a333961373337373436363262616635 +36393432343435343833666537373139663139313038346663653737613737653961613363353131 +6664323739633332300a626437303134353231343735626261353461666538653033323737393564 +63643838393539396437383363666162653732303836616333346231323465633634303633333837 +37343637316464663731646536323233323834333733343366303233346565363362326430326165 +66326431646637316463653662636566346633333231666438336432303332633939323033656361 +35383466373366323863623830383236306331646439623961313035616530646237393732303233 +66333433333732396238323739643162396563373831636466383938613061383832363561613763 +39633463623739373366626362346633306261623764333337346361366165633630613536636537 +36663231326462613438653138316536653730333436663936326632383265336638646263303835 +33393737366533666236323239616636366663643533373634613330373632393634323737393331 +32313464376637333366666534363439313163323932313436646263666364363539333737316634 +63653939353361383733303733383433393966646139643836333834613764323861353431346164 +35626535616539323063333933383766363732633765306366333434343131303635306334353930 +35303661313864346338373138643932346438313662333462613235303662363238373663626233 +37396632613462623765636133356231386533376339386231383739383235323232643531613438 +6333386430316132383233663961333266346130633339396432 diff --git a/ansible/inventory/hosts.ini b/ansible/inventory/hosts.ini new file mode 100644 index 0000000000..c3d178a7c3 --- /dev/null +++ b/ansible/inventory/hosts.ini @@ -0,0 +1,5 @@ +[webservers] +aws-vm ansible_host=54.90.150.210 ansible_user=ubuntu + +[all:vars] +ansible_python_interpreter=/usr/bin/python3 \ No newline at end of file diff --git a/ansible/playbooks/deploy.yml b/ansible/playbooks/deploy.yml new file mode 100644 index 0000000000..95174b9e0e --- /dev/null +++ b/ansible/playbooks/deploy.yml @@ -0,0 +1,7 @@ +--- +- name: Deploy application + hosts: webservers + become: true + + roles: + - web_app diff --git a/ansible/roles/common/defaults/main.yml b/ansible/roles/common/defaults/main.yml new file mode 100644 index 0000000000..68a5c24293 --- /dev/null +++ b/ansible/roles/common/defaults/main.yml @@ -0,0 +1,12 @@ +--- +common_packages: + - python3-pip + - curl + - git + - vim + - htop + - wget + - ca-certificates + - apt-transport-https + - gnupg + - lsb-release \ No newline at end of file diff --git a/ansible/roles/common/tasks/main.yml b/ansible/roles/common/tasks/main.yml new file mode 100644 index 0000000000..0a655e9652 --- /dev/null +++ b/ansible/roles/common/tasks/main.yml @@ -0,0 +1,52 @@ +--- +- name: Update and install packages + block: + - name: Update apt cache + ansible.builtin.apt: + update_cache: true + cache_valid_time: 3600 + + - name: Install common packages + ansible.builtin.apt: + name: "{{ common_packages }}" + state: present + + rescue: + - name: Retry apt update with fix-missing + ansible.builtin.apt: + update_cache: true + update_cache_retries: 5 + cache_valid_time: 3600 + register: common_apt_retry + + - name: Fail if apt update still failed + ansible.builtin.fail: + msg: "apt cache update failed even after retry" + when: common_apt_retry is failed + + always: + - name: Log package installation completion + ansible.builtin.copy: + content: "Package installation completed at {{ ansible_date_time.iso8601 }}\n" + dest: "/tmp/common_role_completion.log" + mode: '0644' + + tags: + - packages + +- name: Configure system + block: + - name: Set timezone to UTC + community.general.timezone: + name: UTC + + always: + - name: Log system configuration completion + ansible.builtin.copy: + content: "System configuration completed at {{ ansible_date_time.iso8601 }}\n" + dest: "/tmp/system_config_completion.log" + mode: '0644' + + tags: + - system + - common \ No newline at end of file diff --git a/ansible/roles/docker/defaults/main.yml b/ansible/roles/docker/defaults/main.yml new file mode 100644 index 0000000000..c84bc2a972 --- /dev/null +++ b/ansible/roles/docker/defaults/main.yml @@ -0,0 +1,3 @@ +docker_version: "24.0" +docker_users: + - ubuntu \ No newline at end of file diff --git a/ansible/roles/docker/handlers/main.yml b/ansible/roles/docker/handlers/main.yml new file mode 100644 index 0000000000..38c68759bd --- /dev/null +++ b/ansible/roles/docker/handlers/main.yml @@ -0,0 +1,8 @@ +--- +- name: Restart Docker + ansible.builtin.service: + name: docker + state: restarted + enabled: true + tags: + - docker \ No newline at end of file diff --git a/ansible/roles/docker/tasks/main.yml b/ansible/roles/docker/tasks/main.yml new file mode 100644 index 0000000000..7d2a6d158b --- /dev/null +++ b/ansible/roles/docker/tasks/main.yml @@ -0,0 +1,90 @@ +--- +- name: Docker installation and setup + block: + - name: Install Docker prerequisites + ansible.builtin.apt: + name: + - apt-transport-https + - ca-certificates + - curl + - gnupg + - lsb-release + state: present + + - name: Add Docker GPG key + ansible.builtin.apt_key: + url: https://download.docker.com/linux/ubuntu/gpg + state: present + + - name: Add Docker repository + ansible.builtin.apt_repository: + repo: "deb https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable" + state: present + + - name: Install Docker packages + ansible.builtin.apt: + name: + - docker-ce + - docker-ce-cli + - containerd.io + state: present + + rescue: + - name: Wait before retrying + ansible.builtin.pause: + seconds: 10 + + - name: Retry apt update + ansible.builtin.apt: + update_cache: true + cache_valid_time: 3600 + register: docker_apt_retry + + - name: Retry Docker installation + ansible.builtin.apt: + name: + - docker-ce + - docker-ce-cli + - containerd.io + state: present + + always: + - name: Ensure Docker service is started and enabled + ansible.builtin.service: + name: docker + state: started + enabled: true + + - name: Log Docker installation completion + ansible.builtin.copy: + content: "Docker installation completed at {{ ansible_date_time.iso8601 }}\n" + dest: "/tmp/docker_install_completion.log" + mode: '0644' + + tags: + - docker + - docker_install + +- name: Docker user configuration + block: + - name: Add ubuntu user to docker group + ansible.builtin.user: + name: ubuntu + groups: docker + append: true + + - name: Install python3-docker via apt + ansible.builtin.apt: + name: python3-docker + state: present + + always: + - name: Log Docker user configuration completion + ansible.builtin.copy: + content: "Docker user configuration completed at {{ ansible_date_time.iso8601 }}\n" + dest: "/tmp/docker_config_completion.log" + mode: '0644' + + tags: + - docker + - docker_install \ No newline at end of file diff --git a/ansible/roles/web_app/defaults/main.yml b/ansible/roles/web_app/defaults/main.yml new file mode 100644 index 0000000000..9cc243e82f --- /dev/null +++ b/ansible/roles/web_app/defaults/main.yml @@ -0,0 +1,22 @@ +--- +# Application Configuration +web_app_name: devops-app +web_app_docker_image: sunflye/devops-info-service +web_app_docker_tag: latest +web_app_port: 5000 +web_app_internal_port: 5000 + +# Docker Compose Configuration +web_app_compose_project_dir: "/opt/{{ web_app_name }}" +web_app_docker_compose_version: "3.8" + +# Wipe Logic Control +web_app_wipe: false + +# Restart policy +web_app_restart_policy: unless-stopped + +# Documentation: +# Set to true to remove application completely +# Wipe only: ansible-playbook deploy.yml -e "web_app_wipe=true" --tags web_app_wipe +# Clean install: ansible-playbook deploy.yml -e "web_app_wipe=true" diff --git a/ansible/roles/web_app/handlers/main.yml b/ansible/roles/web_app/handlers/main.yml new file mode 100644 index 0000000000..87e8ed480a --- /dev/null +++ b/ansible/roles/web_app/handlers/main.yml @@ -0,0 +1,8 @@ +--- +- name: Restart app + community.docker.docker_compose_v2: + project_src: "{{ web_app_compose_project_dir }}" + state: present + pull: always + tags: + - web_app diff --git a/ansible/roles/web_app/meta/main.yml b/ansible/roles/web_app/meta/main.yml new file mode 100644 index 0000000000..4739209626 --- /dev/null +++ b/ansible/roles/web_app/meta/main.yml @@ -0,0 +1,6 @@ +--- +dependencies: + - role: docker + vars: + docker_users: + - ubuntu diff --git a/ansible/roles/web_app/tasks/main.yml b/ansible/roles/web_app/tasks/main.yml new file mode 100644 index 0000000000..c1af05f290 --- /dev/null +++ b/ansible/roles/web_app/tasks/main.yml @@ -0,0 +1,77 @@ +--- +# Wipe logic runs first (when explicitly requested) +- name: Include wipe tasks + ansible.builtin.include_tasks: wipe.yml + tags: + - web_app_wipe + +# Now deploy with Docker Compose +- name: Deploy application with Docker Compose + tags: + - app_deploy + - compose + - web_app + block: + - name: Remove old container (idempotent) + community.docker.docker_container: + name: "{{ web_app_name }}" + state: absent + failed_when: false + + - name: Create application directory + ansible.builtin.file: + path: "{{ web_app_compose_project_dir }}" + state: directory + mode: '0755' + + - name: Template docker-compose.yml + ansible.builtin.template: + src: docker-compose.yml.j2 + dest: "{{ web_app_compose_project_dir }}/docker-compose.yml" + mode: '0644' + register: web_app_compose_template + + - name: Deploy with Docker Compose + community.docker.docker_compose_v2: + project_src: "{{ web_app_compose_project_dir }}" + state: present + pull: missing + recreate: auto + register: web_app_compose_result + + - name: Wait for application to be ready + ansible.builtin.wait_for: + port: "{{ web_app_port }}" + delay: 2 + timeout: 30 + + - name: Verify health endpoint + ansible.builtin.uri: + url: "http://localhost:{{ web_app_port }}/health" + status_code: 200 + register: web_app_health_check + retries: 5 + delay: 5 + + - name: Display health check result + ansible.builtin.debug: + msg: "✅ Application is healthy: {{ web_app_health_check.json.status | default('ok') }}" + + rescue: + - name: Log deployment failure + ansible.builtin.debug: + msg: "Deployment failed, attempting rollback" + + - name: Rollback deployment + community.docker.docker_compose_v2: + project_src: "{{ web_app_compose_project_dir }}" + state: absent + failed_when: false + + always: + - name: Log deployment completion + ansible.builtin.copy: + content: "Deployment completed at {{ ansible_date_time.iso8601 }}\n" + dest: "/tmp/web_app_deployment.log" + mode: '0644' + force: false diff --git a/ansible/roles/web_app/tasks/wipe.yml b/ansible/roles/web_app/tasks/wipe.yml new file mode 100644 index 0000000000..dc6b8a5b87 --- /dev/null +++ b/ansible/roles/web_app/tasks/wipe.yml @@ -0,0 +1,27 @@ +--- +- name: Wipe web application + when: web_app_wipe | bool + tags: + - web_app_wipe + block: + - name: Stop and remove containers with Docker Compose + community.docker.docker_compose_v2: + project_src: "{{ web_app_compose_project_dir }}" + state: absent + failed_when: false + + - name: Remove docker-compose.yml file + ansible.builtin.file: + path: "{{ web_app_compose_project_dir }}/docker-compose.yml" + state: absent + failed_when: false + + - name: Remove application directory + ansible.builtin.file: + path: "{{ web_app_compose_project_dir }}" + state: absent + failed_when: false + + - name: Log wipe completion + ansible.builtin.debug: + msg: "✅ Application {{ web_app_name }} wiped successfully" diff --git a/ansible/roles/web_app/templates/docker-compose.yml.j2 b/ansible/roles/web_app/templates/docker-compose.yml.j2 new file mode 100644 index 0000000000..801205a89d --- /dev/null +++ b/ansible/roles/web_app/templates/docker-compose.yml.j2 @@ -0,0 +1,16 @@ +services: + {{ web_app_name }}: + image: {{ web_app_docker_image }}:{{ web_app_docker_tag }} + container_name: {{ web_app_name }} + ports: + - "{{ web_app_port }}:{{ web_app_internal_port }}" + environment: + PORT: "{{ web_app_internal_port }}" + HOST: "0.0.0.0" + restart: {{ web_app_restart_policy }} + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:{{ web_app_internal_port }}/health"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 10s \ No newline at end of file diff --git a/app-python-policy.hcl b/app-python-policy.hcl new file mode 100644 index 0000000000..5c46778d10 --- /dev/null +++ b/app-python-policy.hcl @@ -0,0 +1,3 @@ +path "secret/data/app-python/*" { + capabilities = ["read"] +} \ No newline at end of file diff --git a/app_python/.coverage b/app_python/.coverage new file mode 100644 index 0000000000..08147fda21 Binary files /dev/null and b/app_python/.coverage differ diff --git a/app_python/.dockerignore b/app_python/.dockerignore new file mode 100644 index 0000000000..fbf4513ce8 --- /dev/null +++ b/app_python/.dockerignore @@ -0,0 +1,21 @@ +# Python cache and build artifacts +__pycache__/ +*.pyc +*.pyo +*.egg-info/ +dist/ +build/ + +# Virtual environments +venv/ +.env + +# System and IDE files +.DS_Store +*.log + +# Version control +.git + +# Documentation and screenshots (not needed in container) +docs/screenshots/ \ No newline at end of file diff --git a/app_python/.gitignore b/app_python/.gitignore new file mode 100644 index 0000000000..3d24680a9d --- /dev/null +++ b/app_python/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +*.pyc +*.egg-info/ +dist/ +build/ +venv/ +env/ +.env +.DS_Store +*.log \ No newline at end of file diff --git a/app_python/Dockerfile b/app_python/Dockerfile new file mode 100644 index 0000000000..e0258001ab --- /dev/null +++ b/app_python/Dockerfile @@ -0,0 +1,21 @@ +FROM python:3.13-slim + +# Create non-root user with home directory and bash shell +RUN useradd --create-home --shell /bin/bash appuser + +WORKDIR /app + +# Copy only requirements.txt first for better layer caching +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +# Copy only necessary files (source code and docs) +COPY app.py . + +# Switch to non-root user +USER appuser + +EXPOSE 5000 + +CMD ["python", "app.py"] \ No newline at end of file diff --git a/app_python/README.md b/app_python/README.md new file mode 100644 index 0000000000..9bc4c8e2d4 --- /dev/null +++ b/app_python/README.md @@ -0,0 +1,280 @@ +# DevOps Info Service + +## Overview + +Simple Flask-based REST API service that provides comprehensive system and runtime information. + +## Prerequisites + +- Python 3.10+ +- pip +- Git + +## Installation + +Clone repository and navigate to app_python: +``` +cd app_python +``` +Install dependencies: + +```bash +python -m venv venv +source venv/bin/activate # Linux/Mac +venv\Scripts\activate # Windows +pip install -r requirements.txt +``` + +## Running the Application + +Run with default configuration: +```bash +python app.py +``` + +Or with custom configuration: + +```bash +PORT=8080 HOST=127.0.0.1 python app.py +DEBUG=true python app.py +``` + +## API Endpoints + +### GET / + +Returns complete service and system information. + +```bash +curl http://localhost:5000 +``` + +### GET /health + +Health check for monitoring and probes. + +```bash +curl http://localhost:5000/health +``` + + +## Configuration + +| Variable | Default | Description | +|----------|---------|-------------| +| `HOST` | `0.0.0.0` | Server host | +| `PORT` | `5000` | Server port | +| `DEBUG` | `False` | Enable debug mode | + +## Docker + +You can run this application in a container using Docker. + +### Build the image locally + +```bash +docker build -t /devops-info-service:latest . +``` +- Replace `` with your Docker Hub username. +- This command builds the image from the Dockerfile in the current directory. + +### Run a container + +```bash +docker run -p 5000:5000 /devops-info-service:latest +``` +- Maps container port 5000 to host port 5000. +- The app will be available at `http://localhost:5000`. + +### Pull from Docker Hub + +```bash +docker pull /devops-info-service:latest + +docker run -p 5000:5000 /devops-info-service:latest +``` +- Pulls the latest published image from Docker Hub and runs it. + +--- + + +## Testing + +### Run tests locally + +Install test dependencies (if not already in requirements.txt): +```bash +pip install pytest pytest-cov +``` + +Run all tests: +```bash +pytest tests/ -v +``` + +Run with coverage report: +```bash +pytest tests/ -v --cov=app --cov-report=term --cov-report=html +``` + +Run specific test class: +```bash +pytest tests/test_app.py::TestMainEndpoint -v +``` + +Run specific test: +```bash +pytest tests/test_app.py::TestMainEndpoint::test_main_endpoint_status_code -v +``` + +### Test Coverage + +Current test coverage: **89%** of application code + +Tests cover: +- **GET /** endpoint - JSON structure, data types, all required fields +- **GET /health** endpoint - Status, timestamp, uptime +- **Error handling** - 404 responses and error JSON format +- **Data type validation** - Response field types verification + + +### CI/CD Automated Testing + +Tests run automatically on: +- Every push to `master` or `lab03` branch +- Every pull request to `master` branch + +See workflow status badge above for latest test results. + +## CI/CD Status + +[![Python CI/CD](https://github.com/sunflye/DevOps-course/actions/workflows/python-ci.yml/badge.svg)](https://github.com/sunflye/DevOps-course/actions/workflows/python-ci.yml) + + +## Visit Counter (Lab 12 — Task 1: Application Persistence Upgrade) + +The application tracks visit counts in a persistent file (`/data/visits`). The counter: +- Increments on each `GET /` request +- Persists across container restarts +- Can be read via `GET /visits` endpoint +- Uses thread-safe file locking (`threading.Lock`) to prevent race conditions + +### Implementation Pattern + +``` +Request to / → Read counter from file → Increment → Write back → Return response +Request to /visits → Read counter from file → Return count +``` + +### Counter Functions + +```python +def read_visits(): + """Read visits count from file.""" + try: + if os.path.exists(VISITS_FILE): + with open(VISITS_FILE, 'r') as f: + return int(f.read().strip()) + except (IOError, ValueError): + pass + return 0 + +def write_visits(count): + """Write visits count to file.""" + with open(VISITS_FILE, 'w') as f: + f.write(str(count)) + +def increment_visits(): + """Safely increment visits counter.""" + with visits_lock: + count = read_visits() + count += 1 + write_visits(count) + return count +``` + +### Testing Persistence + +```powershell +# 1. Start container +docker-compose up -d + +# 2. Make requests (each increments counter) +curl http://localhost:5000/ +curl http://localhost:5000/ +curl http://localhost:5000/visits + +# Output: {"visits":2,"timestamp":"2026-04-11T19:40:40.821933+00:00Z"} + +# 3. Check file on host +cat data/visits +# Output: 2 + +# 4. Stop container +docker-compose stop + +# 5. Verify file persisted (not deleted!) +cat data/visits +# Output: 2 + +# 6. Restart container +docker-compose up -d +Start-Sleep -Seconds 3 + +# 7. Counter should NOT reset +curl http://localhost:5000/visits +# Output: {"visits":2,...} + +# 8. Make new request +curl http://localhost:5000/ + +# 9. Counter continues from 2 → 3 +curl http://localhost:5000/visits +# Output: {"visits":3,...} + +cat data/visits +# Output: 3 +``` + +### Docker Compose Volume Mount + +```yaml +# docker-compose.yml +volumes: + - ./data:/data +``` + +**Configuration:** +- `./data` — host directory (persists after container stops) +- `/data` — container directory (where app writes visits file) + +**Benefits:** +- ✅ Data persists on host after container stops +- ✅ Easy access to files from host machine +- ✅ Volume survives container restarts +- ✅ Multiple containers can share data + +### Thread Safety + +Uses `threading.Lock()` to ensure atomic operations when multiple requests arrive simultaneously: + +```python +visits_lock = threading.Lock() + +def increment_visits(): + with visits_lock: # Prevents race conditions + count = read_visits() + count += 1 + write_visits(count) + return count +``` + +### Endpoints + +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/` | GET | Service information (increments visit counter) | +| `/visits` | GET | Returns current visit count with timestamp | +| `/health` | GET | Health check | +| `/metrics` | GET | Prometheus metrics | +| `/ready` | GET | Readiness check | diff --git a/app_python/app.py b/app_python/app.py new file mode 100644 index 0000000000..3477265301 --- /dev/null +++ b/app_python/app.py @@ -0,0 +1,248 @@ +import os +import socket +import platform +import logging +import json +import time +import threading +from datetime import datetime, timezone +from pathlib import Path +from flask import Flask, jsonify, request, Response, g +from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST + +app = Flask(__name__) + +# ==================== Configuration ==================== +HOST = os.getenv("HOST", "0.0.0.0") +PORT = int(os.getenv("PORT", 5000)) +DEBUG = os.getenv("DEBUG", "False").lower() == "true" + +# ✅ базовый каталог рядом с app.py +BASE_DIR = Path(__file__).resolve().parent +# ✅ по умолчанию пишем в локальную папку app_python/data +# в Docker/K8s переопределяется через DATA_DIR=/data +DATA_DIR = os.getenv("DATA_DIR", str(BASE_DIR / "data")) + +START_TIME = datetime.now(timezone.utc) + +# Ensure data directory exists +Path(DATA_DIR).mkdir(parents=True, exist_ok=True) +VISITS_FILE = os.path.join(DATA_DIR, "visits") +visits_lock = threading.Lock() + +# ==================== Visits Counter ==================== +def read_visits(): + """Read visits count from file.""" + try: + if os.path.exists(VISITS_FILE): + with open(VISITS_FILE, 'r') as f: + return int(f.read().strip()) + except (IOError, ValueError): + pass + return 0 + +def write_visits(count): + """Write visits count to file.""" + with open(VISITS_FILE, 'w') as f: + f.write(str(count)) + +def increment_visits(): + """Safely increment visits counter.""" + with visits_lock: + count = read_visits() + count += 1 + write_visits(count) + return count + +# ==================== JSON Logging ==================== +class JSONFormatter(logging.Formatter): + """Custom formatter that outputs JSON logs.""" + def format(self, record): + log_data = { + "timestamp": datetime.now(timezone.utc).isoformat() + "Z", + "level": record.levelname, + "message": record.getMessage(), + "module": record.module, + } + return json.dumps(log_data) + +handler = logging.StreamHandler() +handler.setFormatter(JSONFormatter()) +logger = logging.getLogger(__name__) +logger.handlers.clear() +logger.addHandler(handler) +logger.setLevel(logging.INFO) + +# ==================== Prometheus Metrics ==================== + +# HTTP Request Metrics +http_requests_total = Counter( + 'http_requests_total', + 'Total HTTP requests', + ['method', 'endpoint', 'status'] +) + +http_request_duration_seconds = Histogram( + 'http_request_duration_seconds', + 'HTTP request duration', + ['method', 'endpoint'] +) + +http_requests_in_progress = Gauge( + 'http_requests_in_progress', + 'HTTP requests currently being processed', + ['method', 'endpoint'] +) + +# Application-specific metrics +devops_info_endpoint_calls = Counter( + 'devops_info_endpoint_calls', + 'Endpoint calls', + ['endpoint'] +) + +system_info_collection_seconds = Histogram( + 'devops_info_system_collection_seconds', + 'System info collection time' +) + +# ==================== Helper Functions ==================== +def get_system_info(): + """Collect system information.""" + return { + 'hostname': socket.gethostname(), + 'platform': platform.system(), + 'architecture': platform.machine(), + 'python_version': platform.python_version(), + 'cpu_count': os.cpu_count() or 1, + } + +def get_uptime(): + """Calculate uptime.""" + uptime_seconds = int((datetime.now(timezone.utc) - START_TIME).total_seconds()) + hours = uptime_seconds // 3600 + minutes = (uptime_seconds % 3600) // 60 + return { + 'seconds': uptime_seconds, + 'human': f"{hours} hour, {minutes} minutes" + } + +def get_request_info(): + """Get request information.""" + return { + 'method': request.method, + 'path': request.path, + 'user_agent': request.headers.get('User-Agent', 'unknown'), + 'client_ip': request.remote_addr, + } + +# ==================== Middleware ==================== +@app.before_request +def before_request(): + """Track request start time and increment in-progress gauge.""" + g.start_time = time.time() + method = request.method + endpoint = request.path or '/' + http_requests_in_progress.labels(method=method, endpoint=endpoint).inc() + logger.info(f"Request started: {method} {endpoint}") + +@app.after_request +def after_request(response): + """Track request duration and record metrics.""" + method = request.method + endpoint = request.path or '/' + status = response.status_code + + # Record duration + if hasattr(g, 'start_time'): + duration = time.time() - g.start_time + http_request_duration_seconds.labels(method=method, endpoint=endpoint).observe(duration) + + # Decrement in-progress gauge + http_requests_in_progress.labels(method=method, endpoint=endpoint).dec() + + # Record total requests + http_requests_total.labels(method=method, endpoint=endpoint, status=status).inc() + + logger.info(f"Request completed: {method} {endpoint} {status}") + return response + +# ==================== Routes ==================== +@app.route('/') +def index(): + """Service information endpoint.""" + increment_visits() + devops_info_endpoint_calls.labels(endpoint='/').inc() + + with system_info_collection_seconds.time(): + uptime = get_uptime() + response = { + "service": { + "name": "devops-info-service", + "version": "1.0.0", + "description": "DevOps course info service", + "framework": "Flask", + }, + "system": get_system_info(), + "runtime": { + "uptime_seconds": uptime["seconds"], + "uptime_human": uptime["human"], + "current_time": datetime.now(timezone.utc).isoformat() + "Z", + "timezone": "UTC", + }, + "request": get_request_info(), + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"}, + {"path": "/visits", "method": "GET", "description": "Visit count"}, + {"path": "/metrics", "method": "GET", "description": "Prometheus metrics"}, + ] + } + return jsonify(response) + +@app.route('/visits') +def visits(): + """Return current visit count.""" + count = read_visits() + return jsonify({ + 'visits': count, + 'timestamp': datetime.now(timezone.utc).isoformat() + "Z" + }) + +@app.route('/health') +def health(): + """Health check endpoint.""" + devops_info_endpoint_calls.labels(endpoint='/health').inc() + uptime = get_uptime() + return jsonify({ + 'status': 'healthy', + 'timestamp': datetime.now(timezone.utc).isoformat() + "Z", + 'uptime_seconds': uptime['seconds'] + }) + +@app.route('/metrics') +def metrics(): + """Prometheus metrics endpoint.""" + return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST) + +@app.route('/ready') +def ready(): + """Readiness check endpoint.""" + return jsonify({'ready': True}) + +# ==================== Error Handlers ==================== +@app.errorhandler(404) +def not_found(error): + """Handle 404 errors.""" + return jsonify({'error': 'Not found'}), 404 + +@app.errorhandler(500) +def internal_error(error): + """Handle 500 errors.""" + logger.error(f"Internal error: {error}") + return jsonify({'error': 'Internal server error'}), 500 + +# ==================== Main ==================== +if __name__ == '__main__': + logger.info(f"Starting application on {HOST}:{PORT}") + app.run(host=HOST, port=PORT, debug=DEBUG) diff --git a/app_python/data/visits b/app_python/data/visits new file mode 100644 index 0000000000..301160a930 --- /dev/null +++ b/app_python/data/visits @@ -0,0 +1 @@ +8 \ No newline at end of file diff --git a/app_python/docs/LAB01.md b/app_python/docs/LAB01.md new file mode 100644 index 0000000000..f61a469b96 --- /dev/null +++ b/app_python/docs/LAB01.md @@ -0,0 +1,339 @@ +# Lab 1 — DevOps Info Service: Submission + +## 1. Framework Selection + +### Choice: Flask + +I selected Flask as my web framework for this project. + +### Why Flask? + +| Aspect | Flask | FastAPI | Django | +|--------|-------|---------|--------| +| **Learning Curve** | Easy | Medium | Steep | +| **Minimal Setup** | Yes | Yes | No | +| **Perfect for microservices** | Yes | Yes | No | +| **Dependencies** | Minimal | Minimal | Many | +| **Community** | Excellent | Growing | Largest | +| **Documentation** | Great | Excellent | Excellent | + +**Reasoning:** + +I chose Flask because it is lightweight and designed for building microservices, which is ideal for DevOps applications. The framework is easy to understand - there is minimal magic happening behind the scenes, making it perfect for learning web application fundamentals. + +Flask has minimal dependencies, resulting in smaller Docker images, and its large community provides plenty of ready-made solutions. + + + +--- +## 2. Best Practices Applied + +### Practice 1: Clean Code Organization + +**Code:** +```python +""" +DevOps Info Service +Main application module +""" +import os +import socket +import platform +from datetime import datetime, timezone +from flask import Flask, jsonify, request + +app = Flask(__name__) + +# Configuration +HOST = os.getenv('HOST', '0.0.0.0') +PORT = int(os.getenv('PORT', 5000)) + +def get_system_info(): + """Collect system information.""" + return {...} +``` + +**Why it matters:** +- Module docstring explains purpose +- Imports organized (standard library first, then Flask) +- Constants centralized (HOST, PORT) +- Functions have docstrings +- Clear, readable structure + +--- + +### Practice 2: Error Handling + +**Code:** +```python +@app.errorhandler(404) +def not_found(error): + return jsonify({ + 'error': 'Not Found', + 'message': 'Endpoint does not exist' + }), 404 + +@app.errorhandler(500) +def internal_error(error): + return jsonify({ + 'error': 'Internal Server Error', + 'message': 'An unexpected error occurred' + }), 500 +``` + +**Why it matters:** +- App doesn't crash on errors +- Clients get meaningful responses +- Proper HTTP status codes (404, 500) +- Prevents exposing stack traces + +--- + +### Practice 3: Configuration via Environment Variables + +**Code:** +```python +HOST = os.getenv('HOST', '0.0.0.0') +PORT = int(os.getenv('PORT', 5000)) +``` + +**Usage:** +```bash +python app.py # Uses defaults +PORT=8080 python app.py # Custom port +``` + +**Why it matters:** +- Same code works in dev, test, and prod +- No hardcoded values +- Docker and Kubernetes can inject values easily +- Secrets stay out of code + +--- + +### Practice 4: Logging + +**Code:** +```python +import logging + +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger(__name__) + +logger.info(f"Request: {request.method} {request.path}") +logger.error(f"Error: {error_message}") +``` + +**Why it matters:** +- Can change log level without restarting +- Timestamps help debug timing issues +- Different levels (INFO, WARNING, ERROR) for filtering +- Production monitoring systems read these logs + +--- + +### Practice 5: Version Pinning + +**Code:** +```txt +Flask==3.1.0 +Werkzeug==3.1.2 +``` + +**Why it matters:** +- Exact versions = reproducible builds +- Prevents breaking changes from new versions +- Team members get same dependencies +- Docker images are consistent everywhere +--- + +## 3. API Documentation + +### GET / — Service Information + +**Endpoint:** `http://localhost:5000/` + +**Request:** +```bash +curl http://localhost:5000 | python -m json.tool +``` + +**Response Structure:** +```json +{ + "service": { + "name": "devops-info-service", + "version": "1.0.0", + "description": "DevOps course info service", + "framework": "Flask" + }, + "system": { + "hostname": "MagicBookX16", + "platform": "Windows", + "platform_version": "Windows-11-10.0.26100-SP0", + "architecture": "AMD64", + "cpu_count": 16, + "python_version": "3.13.5" + }, + "runtime": { + "uptime_seconds": 153, + "uptime_human": "0 hour, 2 minutes", + "current_time": "2026-01-27T10:14:48.063022Z", + "timezone": "UTC" + }, + "request": { + "client_ip": "127.0.0.1", + "user_agent": "curl/8.16.0", + "method": "GET", + "path": "/" + }, + "endpoints": [ + { + "path": "/", + "method": "GET", + "description": "Service information" + }, + { + "path": "/health", + "method": "GET", + "description": "Health check" + } + ] +} +``` + +**Response Code:** `200 OK` + +### GET /health — Health Check + +**Endpoint:** `http://localhost:5000/health` + +**Request:** +```bash +curl http://localhost:5000/health | python -m json.tool +``` + +**Response:** +```json +{ + "status": "healthy", + "timestamp": "2026-01-27T10:14:48.063022Z", + "uptime_seconds": 153 +} +``` + +**Response Code:** `200 OK` + +**Why `/health` is important:** +- Kubernetes uses this to check if pod is alive (liveness probe) +- Load balancers use this to know if backend is healthy +- Monitoring systems alert on non-200 responses +- Will be used extensively in Labs 9+ + +### Testing commands + +**With curl (direct output):** +```bash +curl http://localhost:5000 +curl http://localhost:5000/health +``` + +**With curl and JSON formatting:** +```bash +curl http://localhost:5000 | python -m json.tool +curl http://localhost:5000/health | python -m json.tool +``` +--- + +## 4. Testing Evidence + +### Screenshots are located at: +``` +app_python/docs/screenshots/ +``` + +### Terminal output example: + +``` +curl http://localhost:5000 | python -m json.tool + +{ + "endpoints": [ + { + "description": "Service information", + "method": "GET", + "path": "/" + }, + { + "description": "Health check", + "method": "GET", + "path": "/health" + } + ], + "request": { + "client_ip": "127.0.0.1", + "method": "GET", + "path": "/", + "user_agent": "curl/8.16.0" + }, + "runtime": { + "current_time": "2026-01-27T10:40:09.994687Z", + "timezone": "UTC", + "uptime_human": "0 hour, 0 minutes", + "uptime_seconds": 6 + }, + "service": { + "description": "DevOps course info service", + "framework": "Flask", + "name": "devops-info-service", + "version": "1.0.0" + }, + "system": { + "architecture": "AMD64", + "cpu_count": 16, + "hostname": "MagicBookX16", + "platform": "Windows", + "platform_version": "Windows-11-10.0.26100-SP0", + "python_version": "3.13.5" + } +} +``` +--- + +## 5. Challenges & Solutions + +### Challenge 1: Timestamp Format + +**Problem:** +The requirement specified ISO 8601 format with 'Z' suffix for UTC time. + +**Initial attempt:** +```python +'current_time': datetime.now(timezone.utc).isoformat() +# Result: "2026-01-27T10:40:09.994687+00:00" +``` + +**Solution:** +```python +'current_time': datetime.now(timezone.utc).isoformat().replace("+00:00", "") + "Z" +# Result: "2026-01-27T10:40:09.994687Z" +``` + +**Why this matters:** +- Consistent timestamp format across all APIs +- 'Z' is standard ISO 8601 way to indicate UTC +- Other services need to parse timestamps reliably +--- + +## 6. GitHub Community + + +DevOps is fundamentally about collaboration. Stars and follows motivate open-source maintainers to keep improving their projects and help quality projects gain visibility in the community. + +By supporting developers who share knowledge freely, we build a professional network that strengthens the entire ecosystem. When we star and follow projects and people, we contribute to a culture of recognition and growth that benefits everyone in the DevOps community. + +--- + diff --git a/app_python/docs/LAB02.md b/app_python/docs/LAB02.md new file mode 100644 index 0000000000..83b39a848b --- /dev/null +++ b/app_python/docs/LAB02.md @@ -0,0 +1,378 @@ +# Lab 2 — Docker Containerization + +## 1. Docker Best Practices Applied + +### 1.1 Non-root User + +**What:** +A dedicated non-root user (`appuser`) is created and the application runs as this user. + +**Why:** +Running as a non-root user improves container security. If an attacker compromises the container, they do not get root privileges on the host. Many platforms (like Kubernetes) require containers to run as non-root for security compliance. + +**Dockerfile snippet:** +```dockerfile +RUN useradd --create-home --shell /bin/bash appuser +USER appuser +``` + +--- + +### 1.2 Minimal Base Image + +**What:** +The image uses `python:3.13-slim` as the base. + +**Why:** +A slim image reduces the attack surface, download size, and build time. Fewer packages mean fewer vulnerabilities and faster deployments. + +**Dockerfile snippet:** +```dockerfile +FROM python:3.13-slim +``` + +--- + +### 1.3 Layer Caching (Optimized Layer Order) + +**What:** +`requirements.txt` is copied and dependencies are installed before copying the application code. + +**Why:** +This allows Docker to cache the dependency installation layer. If only the code changes, dependencies are not reinstalled, making builds much faster. + +**Dockerfile snippet:** +```dockerfile +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY app.py . +``` + +--- + +### 1.4 .dockerignore + +**What:** +A `.dockerignore` file is used to exclude unnecessary files and directories from the build context. + +**Why:** +This reduces the build context size, speeds up builds, and prevents sensitive or irrelevant files (like `.git`, `__pycache__`, local logs, etc.) from being added to the image. + +**.dockerignore snippet:** +``` +# Python cache and build artifacts +__pycache__/ +*.pyc +*.pyo +*.egg-info/ +dist/ +build/ + +# Virtual environments +venv/ +.env + +# System and IDE files +.DS_Store +*.log + +# Version control +.git + +# Documentation and screenshots (not needed in container) +docs/screenshots/ +``` + +--- + +### 1.5 Only Necessary Files Copied + +**What:** +Only the files required to run the application are copied into the image. + +**Why:** +This keeps the image small and secure, and ensures that development files, tests, and secrets are not present in the production container. + +**Dockerfile snippet:** +```dockerfile +COPY app.py . +COPY requirements.txt . +``` + +--- +## 2. Image Information & Decisions + +### Base Image Chosen and Justification + +**Base image:** +```dockerfile +FROM python:3.13-slim +``` + +**Justification:** +- The `python:3.13-slim` image is an official Python image with unnecessary packages removed. +- It is much smaller than the full Python image, which reduces download time and attack surface. +- The slim variant is recommended for production as it contains only what is needed to run most Python apps, making the image more secure and efficient. + +--- + +### Final Image Size and Assessment + +After building the image, the final size is: + +```bash +sunflye/devops-info-service latest 76fc66edeef2 46 minutes ago 195MB +``` + +**Assessment:** +- The image size is appropriate for a Python web application. +- This is significantly smaller than using the full `python:3.13` image (which can be 1GB+). +- Smaller images are faster to pull, push, and deploy, and reduce storage costs. + +--- + +### Layer Structure Explanation + +**Layer order in Dockerfile:** +1. `FROM python:3.13-slim` — base image layer +2. `RUN useradd -m appuser` — adds non-root user +3. `WORKDIR /app` — sets working directory +4. `COPY requirements.txt .` — copies dependency file +5. `RUN pip install --no-cache-dir -r requirements.txt` — installs dependencies +6. `COPY app.py .` — copies application code +7. `USER appuser` — switches to non-root user +8. `EXPOSE 5000` — documents the port +9. `CMD ["python", "app.py"]` — default command + +**Why this order:** +- Copying `requirements.txt` and installing dependencies before copying the code allows Docker to cache the dependency layer. If only the code changes, dependencies are not reinstalled, making builds much faster. +- Only necessary files are copied, keeping the image small. + +--- + +### Optimization Choices Made + +- **Slim base image:** Reduces size and vulnerabilities. +- **Layer caching:** Dependency installation is cached unless `requirements.txt` changes. +- **.dockerignore:** Excludes unnecessary files from the build context. +- **Non-root user:** Improves security. +- **Only necessary files copied:** Keeps the image minimal and secure. + +## 3. Build & Run Process + +### 3.1 Build the Docker Image + +```bash +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> docker build -t sunflye/devops-info-service:latest . +[+] Building 2.3s (12/12) FINISHED docker:desktop-linux + => [internal] load build definition from Dockerfile 0.0s + => => transferring dockerfile: 487B 0.0s + => [internal] load metadata for docker.io/library/python:3.13-slim 1.8s + => [auth] library/python:pull token for registry-1.docker.io 0.0s + => [internal] load .dockerignore 0.0s + => => transferring context: 322B 0.0s + => [1/6] FROM docker.io/library/python:3.13-slim@sha256:51e1a0a317fdb6e170dc791bbeae63fac5272c82f43958ef74 0.1s + => => resolve docker.io/library/python:3.13-slim@sha256:51e1a0a317fdb6e170dc791bbeae63fac5272c82f43958ef74 0.1s + => [internal] load build context 0.0s + => => transferring context: 63B 0.0s + => CACHED [2/6] RUN useradd --create-home --shell /bin/bash appuser 0.0s + => CACHED [3/6] WORKDIR /app 0.0s + => CACHED [4/6] COPY requirements.txt . 0.0s + => CACHED [5/6] RUN pip install --no-cache-dir -r requirements.txt 0.0s + => CACHED [6/6] COPY app.py . 0.0s + => exporting to image 0.2s + => => exporting layers 0.0s + => => exporting manifest sha256:168b00bf887bfe5bda411d6182ecb84abc821c89c7d9d63b518d9211f821198b 0.0s + => => exporting config sha256:4c6edff8b2bcffb7ebe8b57bcd79f1eda4cfabc2427273bc36da83c9fd75ece6 0.0s + => => exporting attestation manifest sha256:b2c291ac18880145c8e454024f8616f0749704180ed4386e72532bdcbeccb4 0.1s + => => exporting manifest list sha256:9922a56135c0204526ab9d33268d73f1c551b29616ebeae06a4d314f05738fa5 0.0s + => => naming to docker.io/sunflye/devops-info-service:latest 0.0s + => => unpacking to docker.io/sunflye/devops-info-service:latest +``` + +--- + +### 3.2 Run the Container + +```bash +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> docker run -p 5000:5000 sunflye/devops-info-service:latest +2026-02-01 22:03:29,257 - __main__ - INFO - Starting DevOps Info Service v1.0.0 +2026-02-01 22:03:29,257 - __main__ - INFO - Server running at http://0.0.0.0:5000 + * Serving Flask app 'app' + * Debug mode: off +2026-02-01 22:03:29,261 - werkzeug - INFO - WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. + * Running on all addresses (0.0.0.0) + * Running on http://127.0.0.1:5000 + * Running on http://172.17.0.2:5000 +2026-02-01 22:03:29,261 - werkzeug - INFO - Press CTRL+C to quit +``` + +--- + +### 3.3 Test Endpoints + +```bash +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> curl.exe http://localhost:5000 | python -m json.tool + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + 0 0 0 0 0 0 0 0 --:--:100 688 100 688 0 0 29213 0 --:--:-- --:--:-- --:--:-- 29913 +{ + "endpoints": [ + { + "description": "Service information", + "method": "GET", + "path": "/" + }, + { + "description": "Health check", + "method": "GET", + "path": "/health" + } + ], + "request": { + "client_ip": "172.17.0.1", + "method": "GET", + "path": "/", + "user_agent": "curl/8.16.0" + }, + "runtime": { + "current_time": "2026-02-01T22:04:44.576783Z", + "timezone": "UTC", + "uptime_human": "0 hour, 0 minutes", + "uptime_seconds": 28 + }, + "service": { + "description": "DevOps course info service", + "framework": "Flask", + "name": "devops-info-service", + "version": "1.0.0" + }, + "system": { + "architecture": "x86_64", + "cpu_count": 16, + "hostname": "381be4ed45e4", + "platform": "Linux", + "platform_version": "Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.41", + "python_version": "3.13.11" + } +} +``` + +```bash +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> curl.exe http://localhost:5000/health | python -m json.tool + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + 0 0 0 0 0 0 0 0 --:--:100 83 100 83 0 0 2888 0 --:--:-- --:--:-- --:--:-- 2964 +{ + "status": "healthy", + "timestamp": "2026-02-01T22:05:38.098526Z", + "uptime_seconds": 82 +} +``` + +--- + +### 3.4 Docker Hub Repository + +Docker Hub URL: +https://hub.docker.com/r/sunflye/devops-info-service + +### 3.5 Docker Image Push + +**Terminal output showing successful push and authentication:** + +```bash +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> docker login -u sunflye +Info → A Personal Access Token (PAT) can be used instead. +To create a PAT, visit https://app.docker.com/settings + +Password: +Login Succeeded + +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> docker push sunflye/devops-info-service:latest +The push refers to repository [docker.io/sunflye/devops-info-service] +b77222a87dc3: Pushed +3f4b601b9012: Pushed +0bee50492702: Pushed +119d43eec815: Pushed +8843ea38a07e: Pushed +b15e19cfc204: Pushed +38e37d324303: Pushed +b15e19cfc204: Pushed +38e37d324303: Pushed +36b6de65fd8d: Pushed +latest: digest: sha256:76fc66edeef2c1f733dfc3b9d6d1611067f4a67f562442acac079fa7f8358653 size: 856 + +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> docker push sunflye/devops-info-service:v1 +The push refers to repository [docker.io/sunflye/devops-info-service] +38e37d324303: Layer already exists +36b6de65fd8d: Layer already exists +119d43eec815: Layer already exists +8843ea38a07e: Layer already exists +3f4b601b9012: Already exists +b15e19cfc204: Layer already exists +0bee50492702: Layer already exists +1da1696c3b45: Layer already exists +b77222a87dc3: Layer already exists +dff5860bd433: Layer already exists +v1: digest: sha256:76fc66edeef2c1f733dfc3b9d6d1611067f4a67f562442acac079fa7f8358653 size: 856 +``` +### 3.6 Tagging Strategy + +**Explanation:** +- I use two tags for my Docker image: `latest` and `v1`. +- The `latest` tag always points to the most recent build of the image. This is convenient for development, testing, and for users who want the newest version by default. +- The `v1` tag is a versioned tag that represents a stable, production-ready release. Using version tags allows for reproducible deployments and easy rollbacks if needed. +- This strategy follows Docker best practices, making it easy to distinguish between stable releases and ongoing development. + +## 4. Technical Analysis + +### Why does your Dockerfile work the way it does? + +My Dockerfile is organized to make builds fast, images small, and the app secure: + +- I use a minimal Python base image to keep the image size small and reduce security risks. +- I copy requirements.txt and install dependencies before copying the app code. This way, Docker caches the dependencies, so if I only change the code, the build is much faster. +- I create and use a non-root user for better security. +- I only copy the files needed to run the app, so the image does not include unnecessary or sensitive files. +This setup makes the build process efficient and the resulting image safe and lightweight. + +--- + +### What would happen if you changed the layer order? + +If I copied all application files before installing dependencies: +```dockerfile +COPY . . +RUN pip install --no-cache-dir -r requirements.txt +``` +then **any change in the code** would invalidate the cache for the dependencies layer, causing `pip install` to run on every build. +This would make builds much slower and waste resources, especially in CI/CD pipelines. + +--- + +### What security considerations did you implement? + +- **Non-root user:** The container runs as `appuser` instead of root, reducing the risk if the app is compromised. +- **Minimal base image:** Using `python:3.13-slim` reduces the attack surface by including only essential packages. +- **.dockerignore:** Prevents sensitive files (like `.env`, `.git`, logs, and local caches) from being added to the image. +- **No secrets in image:** Only required files are copied; secrets and credentials are not included. + +--- + +### How does .dockerignore improve your build? + +The `.dockerignore` file excludes unnecessary files and directories from the Docker build context: +- **Faster builds:** Less data is sent to the Docker daemon, speeding up the build process. +- **Smaller images:** Unneeded files (like caches, logs, venv, and git history) are not included in the final image. +- **Better security:** Sensitive files (such as `.env` or `.git`) are not accidentally copied into the image. + +### Challenges & Solutions + +**Issue:** +PowerShell vs Bash commands: +Some common Docker commands (like `grep`) do not work in PowerShell, so I had to use `docker images` and find the image manually. + +**Solution:** +I adapted my workflow to use PowerShell-compatible commands and manually checked the output of `docker images` to find the image size and details. + diff --git a/app_python/docs/LAB03.md b/app_python/docs/LAB03.md new file mode 100644 index 0000000000..579f2e5f2a --- /dev/null +++ b/app_python/docs/LAB03.md @@ -0,0 +1,278 @@ +# Lab 3 — Continuous Integration (CI/CD): + +## Task 1 — Unit Testing + +### Testing Framework: pytest + +**Why pytest:** +- Simple, powerful syntax +- Great for testing Flask apps +- Built-in fixtures +- Coverage reporting with pytest-cov + +### Test structure + +Tests in `app_python/tests/test_app.py` cover: +- `GET /` endpoint - JSON structure, all fields, data types +- `GET /health` endpoint - Status, timestamp, uptime +- Error handling (404 responses) +- Data type validation + +The tests are organized into classes by endpoint and purpose: + +- **TestMainEndpoint** — tests for the main `/` endpoint. + Checks status code, content type, presence and structure of all required fields, and correct data types in the main service response. + +- **TestHealthEndpoint** — tests for the `/health` endpoint. + Verifies the health check response, including status, timestamp, and uptime fields. + +- **TestErrorHandling** — tests for error handling (e.g., 404 errors). + Ensures that invalid routes return the correct error code and JSON error format. + +- **TestDataTypes** — tests for data type validation in responses. + Confirms that all fields in the main endpoint response have the expected data types. + +Each class contains multiple test methods to cover both successful and error scenarios, ensuring comprehensive coverage of the application’s API. + +### Running Tests Locally + +```bash +cd app_python +pytest tests/ -v --cov=app --cov-report=term +``` + +### Test Results + +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> pytest tests/ -v --cov=app --cov-report=term +==================================================== test session starts ===================================================== +platform win32 -- Python 3.13.5, pytest-7.4.3, pluggy-1.6.0 -- D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\venv\Scripts\python.exe +cachedir: .pytest_cache +rootdir: D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python +plugins: cov-4.1.0 +collected 15 items + +tests/test_app.py::TestMainEndpoint::test_main_endpoint_status_code PASSED [ 6%] +tests/test_app.py::TestMainEndpoint::test_main_endpoint_content_type PASSED [ 13%] +tests/test_app.py::TestMainEndpoint::test_main_endpoint_service_data PASSED [ 20%] +tests/test_app.py::TestMainEndpoint::test_main_endpoint_system_data PASSED [ 26%] +tests/test_app.py::TestMainEndpoint::test_main_endpoint_runtime_data PASSED [ 33%] +tests/test_app.py::TestMainEndpoint::test_main_endpoint_request_data PASSED [ 40%] +tests/test_app.py::TestMainEndpoint::test_main_endpoint_endpoints_list PASSED [ 46%] +tests/test_app.py::TestHealthEndpoint::test_health_endpoint_status_code PASSED [ 53%] +tests/test_app.py::TestHealthEndpoint::test_health_endpoint_content_type PASSED [ 60%] +tests/test_app.py::TestHealthEndpoint::test_health_endpoint_status_field PASSED [ 66%] +tests/test_app.py::TestHealthEndpoint::test_health_endpoint_timestamp PASSED [ 73%] +tests/test_app.py::TestHealthEndpoint::test_health_endpoint_uptime PASSED [ 80%] +tests/test_app.py::TestErrorHandling::test_404_not_found PASSED [ 86%] +tests/test_app.py::TestErrorHandling::test_404_response_is_json PASSED [ 93%] +tests/test_app.py::TestDataTypes::test_main_endpoint_data_types PASSED [100%] + +---------- coverage: platform win32, python 3.13.5-final-0 ----------- +Name Stmts Miss Cover +---------------------------- +app.py 46 5 89% +---------------------------- +TOTAL 46 5 89% + + +===================================================== 15 passed in 0.35s ===================================================== +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\app_python> +``` + +--- + +## Task 2 — GitHub Actions CI Workflow + +### Workflow Overview + +**File:** `.github/workflows/python-ci.yml` + +The workflow automates: +1. **Code Quality & Testing** - On every push/PR +2. **Linting** - flake8 code quality checks +3. **Docker Build & Push** - Automatic image publishing after tests pass +4. **Versioning** - CalVer strategy + +### Workflow Triggers + +The workflow runs on: +- Push to `master` or `lab3` (full CI/CD, including Docker build and push) +- Pull requests to `master` (runs tests and lint only, no Docker build) +- Git tags starting with `v` (builds and pushes with SemVer tag) + +This ensures that only production-ready code triggers Docker builds, while PRs are tested for quality and correctness before merging. +```yaml +on: + push: + branches: [ master, lab3 ] + tags: + - 'v*' + pull_request: + branches: [ master ] +``` + +**Behavior:** +- **Push to master/lab3:** Run tests → Build Docker image +- **Pull Request to master:** Run tests only (no Docker build) +- **Git tag (v1.0.0):** Run tests → Build Docker image with SemVer version + +### Marketplace Actions Used + +- `actions/checkout@v4`: Official action to clone the repository. +- `actions/setup-python@v5`: Official action to set up Python with caching. +- `docker/login-action@v3`: Secure Docker Hub authentication. +- `docker/build-push-action@v5`: Efficient Docker build and push with caching. +- `codecov/codecov-action@v4`: Uploads coverage reports to Codecov. + +These actions are chosen for reliability, security, and community support. + +### Versioning Strategy: Hybrid (CalVer + SemVer) + +**Default (CalVer):** +- Format: `YYYY.MM.DD` (e.g., 2024.01.27) +- Automatic from build date +- Tags: `sunflye/devops-info-service:2024.01.27` + `latest` + +**On Git Tag (SemVer):** +- Format: `vMAJOR.MINOR.PATCH` (e.g., v1.0.0) +- Manual release tagging +- Tags: `sunflye/devops-info-service:v1.0.0` + `latest` + +**Why this approach?** +- CalVer perfect for continuous deployment +- SemVer useful for explicit releases +- Both approaches provide flexibility + +### Workflow Evidence + +- [![Python CI/CD](https://github.com/sunflye/DevOps-course/actions/workflows/python-ci.yml/badge.svg)](https://github.com/sunflye/DevOps-course/actions/workflows/python-ci.yml) +- ![Green checkmark screenshot](./screenshots/04-workflow.png) + +### Workflow Jobs + +**Job 1: test** +- Checks out code +- Sets up Python 3.13 with pip cache +- Installs dependencies +- Runs flake8 linting +- Runs pytest with coverage +- Uploads coverage to Codecov + +**Job 2: build-and-push** +- Depends on: `test` job (only runs if tests pass) +- Triggers on: push only (not on PR) +- Builds Docker image with Buildx +- Pushes to Docker Hub with 2 tags + + +### Docker Hub Images + +All images available at: +https://hub.docker.com/r/sunflye/devops-info-service + +**Example tags:** +- `sunflye/devops-info-service:2026.02.11` +- `sunflye/devops-info-service:latest` + +--- +## Task 3 — CI Best Practices & Security + +--- + +### Best Practices Applied + +#### 1. **Dependency Caching** +**Implementation:** +```yaml +cache: 'pip' +cache-dependency-path: 'app_python/requirements.txt' +``` +**Why:** Saves 30-60 seconds per build by reusing downloaded packages. + +#### 2. **Job Dependencies (Fail Fast)** +**Implementation:** +```yaml +build-and-push: + needs: test # Only runs if tests pass +``` +**Why:** Prevents broken Docker images from being published. + +#### 3. **Docker Layer Caching** +**Implementation:** +```yaml +cache-from: type=gha +cache-to: type=gha,mode=max +``` +**Why:** Reuses Docker layers, faster builds (especially in rebuild scenarios). + +#### 4. **Secrets Management** +**Implementation:** +- `DOCKER_USERNAME` and `DOCKER_TOKEN` stored as GitHub Secrets +- No credentials hardcoded in workflow files + +**Why:** Security best practice, prevents credential leaks. + +#### 5. **Conditional Triggers** +**Implementation:** +```yaml +if: github.event_name == 'push' # Docker build only on push +``` +**Why:** PRs don't push to Docker Hub, only runs tests. + +#### 6. **Test Coverage Tracking** +**Implementation:** +- pytest-cov generates coverage reports +- Uploaded to Codecov for tracking + +**Why:** Visibility into code coverage trends and quality. + + + + +### Performance Improvements + +**Workflow timing comparison (real runs):** + +| Scenario | Total duration | test job | build-and-push job | +|------------------|---------------|----------|--------------------| +| Without cache | 1m 14s | 40s | 25s | +| With cache | 1m 13s | 39s | 26s | + +
+Without cache + +![Without cache](./screenshots/05-without_cache.png) +
+ +
+With cache + +![With cache](./screenshots/06-with_cache.png) +
+ +**Conclusion:** +In this project, the workflow is already highly optimized, so the difference between runs with and without cache is minimal (about 1 second). +However, in larger projects or with more dependencies, caching can save significant time. + +### Security Scanning (Snyk) + +**Integration:** +- Snyk scans `requirements.txt` for known vulnerabilities +- Configured with `--severity-threshold=high` (only fails on high/critical) +- Runs in parallel with main testing job + +**Results:** +``` +Testing /github/workspace... + +Organization: sunflye +Package manager: pip +Target file: app_python/requirements.txt +Project name: app_python +Open source: no +Project path: /github/workspace +Licenses: enabled + +✔ Tested /github/workspace for known issues, no vulnerable paths found. +``` \ No newline at end of file diff --git a/app_python/docs/screenshots/01-main-endpoint.png b/app_python/docs/screenshots/01-main-endpoint.png new file mode 100644 index 0000000000..50ae1f340c Binary files /dev/null and b/app_python/docs/screenshots/01-main-endpoint.png differ diff --git a/app_python/docs/screenshots/02-health-check.png b/app_python/docs/screenshots/02-health-check.png new file mode 100644 index 0000000000..d53b3ca440 Binary files /dev/null and b/app_python/docs/screenshots/02-health-check.png differ diff --git a/app_python/docs/screenshots/03-formatted-output.png b/app_python/docs/screenshots/03-formatted-output.png new file mode 100644 index 0000000000..6d12f27c52 Binary files /dev/null and b/app_python/docs/screenshots/03-formatted-output.png differ diff --git a/app_python/docs/screenshots/04-workflow.png b/app_python/docs/screenshots/04-workflow.png new file mode 100644 index 0000000000..ff03bc92d9 Binary files /dev/null and b/app_python/docs/screenshots/04-workflow.png differ diff --git a/app_python/docs/screenshots/05-without_cache.png b/app_python/docs/screenshots/05-without_cache.png new file mode 100644 index 0000000000..8702ea8bde Binary files /dev/null and b/app_python/docs/screenshots/05-without_cache.png differ diff --git a/app_python/docs/screenshots/06-with_cache.png b/app_python/docs/screenshots/06-with_cache.png new file mode 100644 index 0000000000..8f92df1189 Binary files /dev/null and b/app_python/docs/screenshots/06-with_cache.png differ diff --git a/app_python/docs/screenshots/07-instanse.png b/app_python/docs/screenshots/07-instanse.png new file mode 100644 index 0000000000..d7a37d1c9b Binary files /dev/null and b/app_python/docs/screenshots/07-instanse.png differ diff --git a/app_python/docs/screenshots/08-persist_lab12.png b/app_python/docs/screenshots/08-persist_lab12.png new file mode 100644 index 0000000000..eef8ee2829 Binary files /dev/null and b/app_python/docs/screenshots/08-persist_lab12.png differ diff --git a/app_python/docs/screenshots/09-CLI.jpg b/app_python/docs/screenshots/09-CLI.jpg new file mode 100644 index 0000000000..89731adf74 Binary files /dev/null and b/app_python/docs/screenshots/09-CLI.jpg differ diff --git a/app_python/docs/screenshots/10-confirm.jpg b/app_python/docs/screenshots/10-confirm.jpg new file mode 100644 index 0000000000..a27cb1053a Binary files /dev/null and b/app_python/docs/screenshots/10-confirm.jpg differ diff --git a/app_python/docs/screenshots/11-confirm.jpg b/app_python/docs/screenshots/11-confirm.jpg new file mode 100644 index 0000000000..dc70ec19cc Binary files /dev/null and b/app_python/docs/screenshots/11-confirm.jpg differ diff --git a/app_python/docs/screenshots/12-confirm.jpg b/app_python/docs/screenshots/12-confirm.jpg new file mode 100644 index 0000000000..ea797e5e76 Binary files /dev/null and b/app_python/docs/screenshots/12-confirm.jpg differ diff --git a/app_python/docs/screenshots/13-confirm.png b/app_python/docs/screenshots/13-confirm.png new file mode 100644 index 0000000000..7e956f3f38 Binary files /dev/null and b/app_python/docs/screenshots/13-confirm.png differ diff --git a/app_python/docs/screenshots/14-confirm.png b/app_python/docs/screenshots/14-confirm.png new file mode 100644 index 0000000000..2c9e3d0986 Binary files /dev/null and b/app_python/docs/screenshots/14-confirm.png differ diff --git a/app_python/docs/screenshots/15-confirm.png b/app_python/docs/screenshots/15-confirm.png new file mode 100644 index 0000000000..1a4eb8d958 Binary files /dev/null and b/app_python/docs/screenshots/15-confirm.png differ diff --git a/app_python/docs/screenshots/16-confirm.jpg b/app_python/docs/screenshots/16-confirm.jpg new file mode 100644 index 0000000000..e6fe129a99 Binary files /dev/null and b/app_python/docs/screenshots/16-confirm.jpg differ diff --git a/app_python/docs/screenshots/17-confirm.png b/app_python/docs/screenshots/17-confirm.png new file mode 100644 index 0000000000..027a3d92e9 Binary files /dev/null and b/app_python/docs/screenshots/17-confirm.png differ diff --git a/app_python/docs/screenshots/18-confirm.jpg b/app_python/docs/screenshots/18-confirm.jpg new file mode 100644 index 0000000000..9969375892 Binary files /dev/null and b/app_python/docs/screenshots/18-confirm.jpg differ diff --git a/app_python/docs/screenshots/19-confirm.png b/app_python/docs/screenshots/19-confirm.png new file mode 100644 index 0000000000..9013ca798d Binary files /dev/null and b/app_python/docs/screenshots/19-confirm.png differ diff --git a/app_python/docs/screenshots/20.jpg b/app_python/docs/screenshots/20.jpg new file mode 100644 index 0000000000..837e7ec966 Binary files /dev/null and b/app_python/docs/screenshots/20.jpg differ diff --git a/app_python/docs/screenshots/21.jpg b/app_python/docs/screenshots/21.jpg new file mode 100644 index 0000000000..d0d20b7977 Binary files /dev/null and b/app_python/docs/screenshots/21.jpg differ diff --git a/app_python/docs/screenshots/22.jpg b/app_python/docs/screenshots/22.jpg new file mode 100644 index 0000000000..6052ed30ee Binary files /dev/null and b/app_python/docs/screenshots/22.jpg differ diff --git a/app_python/docs/screenshots/23.png b/app_python/docs/screenshots/23.png new file mode 100644 index 0000000000..a2f766225a Binary files /dev/null and b/app_python/docs/screenshots/23.png differ diff --git a/app_python/docs/screenshots/24.jpg b/app_python/docs/screenshots/24.jpg new file mode 100644 index 0000000000..9b5cf1aa82 Binary files /dev/null and b/app_python/docs/screenshots/24.jpg differ diff --git a/app_python/docs/screenshots/25.png b/app_python/docs/screenshots/25.png new file mode 100644 index 0000000000..81b1fa7618 Binary files /dev/null and b/app_python/docs/screenshots/25.png differ diff --git a/app_python/docs/screenshots/26.png b/app_python/docs/screenshots/26.png new file mode 100644 index 0000000000..e4c984e83a Binary files /dev/null and b/app_python/docs/screenshots/26.png differ diff --git a/app_python/docs/screenshots/27.png b/app_python/docs/screenshots/27.png new file mode 100644 index 0000000000..9d0b86425e Binary files /dev/null and b/app_python/docs/screenshots/27.png differ diff --git a/app_python/docs/screenshots/28.png b/app_python/docs/screenshots/28.png new file mode 100644 index 0000000000..4845a9e75d Binary files /dev/null and b/app_python/docs/screenshots/28.png differ diff --git a/app_python/docs/screenshots/29.png b/app_python/docs/screenshots/29.png new file mode 100644 index 0000000000..1ecdd4fb04 Binary files /dev/null and b/app_python/docs/screenshots/29.png differ diff --git a/app_python/docs/screenshots/30.png b/app_python/docs/screenshots/30.png new file mode 100644 index 0000000000..a57d0c1875 Binary files /dev/null and b/app_python/docs/screenshots/30.png differ diff --git a/app_python/docs/screenshots/31.png b/app_python/docs/screenshots/31.png new file mode 100644 index 0000000000..d8a1d8d31f Binary files /dev/null and b/app_python/docs/screenshots/31.png differ diff --git a/app_python/docs/screenshots/32.png b/app_python/docs/screenshots/32.png new file mode 100644 index 0000000000..3d1ee16935 Binary files /dev/null and b/app_python/docs/screenshots/32.png differ diff --git a/app_python/requirements.txt b/app_python/requirements.txt new file mode 100644 index 0000000000..88ef246d45 --- /dev/null +++ b/app_python/requirements.txt @@ -0,0 +1,5 @@ +Flask==3.1.0 +Werkzeug==3.1.2 +pytest==7.4.3 +pytest-cov==4.1.0 +prometheus-client==0.23.1 \ No newline at end of file diff --git a/app_python/tests/__init__.py b/app_python/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app_python/tests/test_app.py b/app_python/tests/test_app.py new file mode 100644 index 0000000000..895fe91222 --- /dev/null +++ b/app_python/tests/test_app.py @@ -0,0 +1,176 @@ +import pytest +from app import app + + +@pytest.fixture +def client(): + """Create a test client for the Flask application.""" + app.config['TESTING'] = True + with app.test_client() as client: + yield client + + +class TestMainEndpoint: + """Tests for GET / endpoint""" + + def test_main_endpoint_status_code(self, client): + """Test that main endpoint returns 200""" + response = client.get('/') + assert response.status_code == 200 + + def test_main_endpoint_content_type(self, client): + """Test that response is JSON""" + response = client.get('/') + assert response.content_type == 'application/json' + + def test_main_endpoint_service_data(self, client): + """Test that service metadata is present""" + response = client.get('/') + data = response.get_json() + + assert 'service' in data + assert data['service']['name'] == 'devops-info-service' + assert data['service']['version'] == '1.0.0' + assert data['service']['framework'] == 'Flask' + + def test_main_endpoint_system_data(self, client): + """Test that system information is present""" + response = client.get('/') + data = response.get_json() + + assert 'system' in data + assert 'hostname' in data['system'] + assert 'platform' in data['system'] + assert 'architecture' in data['system'] + assert 'cpu_count' in data['system'] + assert 'python_version' in data['system'] + + def test_main_endpoint_runtime_data(self, client): + """Test that runtime information is present""" + response = client.get('/') + data = response.get_json() + + assert 'runtime' in data + assert 'uptime_seconds' in data['runtime'] + assert 'uptime_human' in data['runtime'] + assert 'current_time' in data['runtime'] + assert 'timezone' in data['runtime'] + + # Verify uptime_seconds is non-negative integer + assert isinstance(data['runtime']['uptime_seconds'], int) + assert data['runtime']['uptime_seconds'] >= 0 + + def test_main_endpoint_request_data(self, client): + """Test that request information is present""" + response = client.get('/') + data = response.get_json() + + assert 'request' in data + assert 'client_ip' in data['request'] + assert 'user_agent' in data['request'] + assert 'method' in data['request'] + assert 'path' in data['request'] + + # Verify HTTP method + assert data['request']['method'] == 'GET' + assert data['request']['path'] == '/' + + def test_main_endpoint_endpoints_list(self, client): + """Test that endpoints list is present""" + response = client.get('/') + data = response.get_json() + + assert 'endpoints' in data + assert isinstance(data['endpoints'], list) + assert len(data['endpoints']) == 4 + + # Verify endpoints structure + paths = [ep['path'] for ep in data['endpoints']] + assert '/' in paths + assert '/health' in paths + assert '/metrics' in paths + + +class TestHealthEndpoint: + """Tests for GET /health endpoint""" + + def test_health_endpoint_status_code(self, client): + """Test that health endpoint returns 200""" + response = client.get('/health') + assert response.status_code == 200 + + def test_health_endpoint_content_type(self, client): + """Test that response is JSON""" + response = client.get('/health') + assert response.content_type == 'application/json' + + def test_health_endpoint_status_field(self, client): + """Test that status field is healthy""" + response = client.get('/health') + data = response.get_json() + + assert 'status' in data + assert data['status'] == 'healthy' + + def test_health_endpoint_timestamp(self, client): + """Test that timestamp is present""" + response = client.get('/health') + data = response.get_json() + + assert 'timestamp' in data + assert isinstance(data['timestamp'], str) + # Verify ISO 8601 format with Z suffix + assert data['timestamp'].endswith('Z') + + def test_health_endpoint_uptime(self, client): + """Test that uptime_seconds is present""" + response = client.get('/health') + data = response.get_json() + + assert 'uptime_seconds' in data + assert isinstance(data['uptime_seconds'], int) + assert data['uptime_seconds'] >= 0 + + +class TestErrorHandling: + """Tests for error handling""" + + def test_404_not_found(self, client): + """Test that invalid endpoint returns 404""" + response = client.get('/nonexistent') + assert response.status_code == 404 + + data = response.get_json() + assert 'error' in data + + def test_404_response_is_json(self, client): + """Test that 404 response is JSON""" + response = client.get('/invalid-endpoint') + assert response.content_type == 'application/json' + + +class TestDataTypes: + """Tests for data type validation""" + + def test_main_endpoint_data_types(self, client): + """Test that response data types are correct""" + response = client.get('/') + data = response.get_json() + + # Service + assert isinstance(data['service']['name'], str) + assert isinstance(data['service']['version'], str) + + # System + assert isinstance(data['system']['hostname'], str) + assert isinstance(data['system']['platform'], str) + assert isinstance(data['system']['cpu_count'], int) + + # Runtime + assert isinstance(data['runtime']['uptime_seconds'], int) + assert isinstance(data['runtime']['uptime_human'], str) + assert isinstance(data['runtime']['timezone'], str) + + # Request + assert isinstance(data['request']['method'], str) + assert isinstance(data['request']['path'], str) \ No newline at end of file diff --git a/data/visits b/data/visits new file mode 100644 index 0000000000..301160a930 --- /dev/null +++ b/data/visits @@ -0,0 +1 @@ +8 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000..bccef12487 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,27 @@ +version: '3.8' + +services: + app-python: + build: + context: ./app_python + dockerfile: Dockerfile + container_name: app-python + ports: + - "5000:5000" + environment: + HOST: "0.0.0.0" + PORT: "5000" + DATA_DIR: "/data" + DEBUG: "False" + volumes: + - ./data:/data + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:5000/health"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 5s + +volumes: + data: diff --git a/docs/LAB04.md b/docs/LAB04.md new file mode 100644 index 0000000000..48889c68e3 --- /dev/null +++ b/docs/LAB04.md @@ -0,0 +1,386 @@ +# Lab 4 — Infrastructure as Code (Terraform & Pulumi) + +## Task 1 — Terraform VM Creation + +### 1. Cloud Provider & Infrastructure + +**Cloud Provider:** AWS + +**Why AWS?** +- Offers Free Tier: 750 hours/month for `t2.micro`—perfect for labs and testing. +- Most popular and widely adopted cloud provider. +- Extensive documentation and community support. +- Free for 12 months for new accounts. + +**Instance Type/Size and Why:** +- `t2.micro` (smallest free tier, sufficient for basic server/app deployment). + +**Region/Zone Selected:** +- `us-east-1` (commonly chosen for AWS labs). + +**Total Cost:** $0 (AWS Free Tier). + +**Resources Created:** +- **VM Instance:** `t2.micro`, tagged as `devops-lab-vm`. +- **Network:** Default AWS VPC in region `us-east-1`. +- **Security Group/Firewall:** + - SSH (22) open to all (`0.0.0.0/0`) + - HTTP (80) open to all (`0.0.0.0/0`) + - App port (5000) open to all (`0.0.0.0/0`) +- **Public IP:** Assigned automatically at creation. _(Note: may change on stop/start unless Elastic IP attached)_ + +![Instance example](/app_python/docs/screenshots/07-instanse.png) + +--- + +### 2. Terraform Implementation + +**Terraform Version:** +```bash +terraform version +Terraform v1.14.5 +on windows_amd64 ++ provider registry.terraform.io/hashicorp/aws v6.32.1 +``` + +**Project Structure:** +``` +terraform/ +├── main.tf +├── variables.tf +├── outputs.tf +└── .gitignore + +``` + +**Key Configuration Decisions:** +- Used variables for region, instance type, AMI, and key name. +- All essential ports opened (22, 80, 5000) for lab/demo purposes. +- Used default VPC (no explicit custom VPC for simplicity and to stay in Free Tier). +- Output public IP and ready-to-use SSH command. +- Sensitive files (`*.tfstate`, `*.pem`, `.terraform/`) included in `.gitignore`. + + + +--- + +**Terminal output from key commands:** + +**terraform init** + +```plaintext +Initializing the backend... +Initializing provider plugins... +Terraform has been successfully initialized! +``` + +**terraform plan** +```plaintext +Terraform will perform the following actions: + + # aws_instance.vm will be created + + resource "aws_instance" "vm" { + + ami = "ami-0b6c6ebed2801a5cb" + + instance_type = "t2.micro" + + key_name = "vockey" + + tags = { + + "Name" = "devops-lab-vm" + } + ... + } + + # aws_security_group.vm_sg will be created + + resource "aws_security_group" "vm_sg" { + + description = "Allow SSH, HTTP, 5000" + + ingress = [ + + { from_port = 22, to_port = 22, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"], description = "SSH" }, + + { from_port = 80, to_port = 80, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"], description = "HTTP" }, + + { from_port = 5000, to_port = 5000, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"], description = "Custom App" }, + ] + ... + } + +Plan: 2 to add, 0 to change, 0 to destroy. +``` + +**terraform apply** +```plaintext +... +Apply complete! Resources: 2 added, 0 changed, 0 destroyed. + +Outputs: + +public_ip = "34.233.135.93" +ssh_command = "ssh -i labsuser.pem ubuntu@34.233.135.93" +``` + +**Public IP of created VM:** +``` +34.233.135.93 +``` +--- + +**SSH Connection proof:** + +```plaintext +$ ssh -i labsuser.pem ubuntu@34.233.135.93 +Welcome to Ubuntu 24.04.3 LTS (GNU/Linux 6.14.0-1018-aws x86_64) +... +Last login: Tue Feb 17 19:06:59 2026 from ... +ubuntu@ip-172-31-20-177:~$ +``` + +--- +## Task 2 — Pulumi VM Creation + +--- + +### 1. Programming Language Chosen for Pulumi + +I chose **Python** as the language for my Pulumi implementation because it is widely supported and allows use of rich programming constructs for infrastructure as code. + +**Pulumi Version:** +```bash +pulumi version +v3.220.0 +``` +--- + + +### 2. Terraform Destroy Output + +```text +Changes to Outputs: + - public_ip = "34.233.135.93" -> null + - ssh_command = "ssh ubuntu@34.233.135.93" -> null + +Do you really want to destroy all resources? + Terraform will destroy all your managed infrastructure, as shown above. + There is no undo. Only 'yes' will be accepted to confirm. + + Enter a value: yes + +aws_instance.vm: Destroying... [id=i-0122876d4c3947bed] +aws_instance.vm: Still destroying... [id=i-0122876d4c3947bed, 00m10s elapsed] +aws_instance.vm: Destruction complete after 1m2s +aws_security_group.vm_sg: Destroying... [id=sg-0e45f22278a7b1970] +aws_security_group.vm_sg: Destruction complete after 1s + +Destroy complete! Resources: 2 destroyed. +``` + +--- + +### 3. Pulumi Preview and Up Output + +#### pulumi preview: +```text +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\pulumi> pulumi preview +Enter your passphrase to unlock config/secrets + Type Name Plan + + pulumi:pulumi:Stack devops-lab04-dev create + + ├─ aws:ec2:SecurityGroup vm-sg create + + └─ aws:ec2:Instance devops-lab-vm create +Outputs: + public_ip : [unknown] + ssh_command: [unknown] + +Resources: + + 3 to create +``` + +#### pulumi up: +```text +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\pulumi> pulumi up +Previewing update (dev): + Type Name Plan + pulumi:pulumi:Stack devops-lab04-dev + + └─ aws:ec2:Instance devops-lab-vm create +Outputs: + + public_ip : [unknown] + + ssh_command: [unknown] + +Resources: + + 1 to create + 2 unchanged + +Do you want to perform this update? yes +Updating (dev): + Type Name Status + pulumi:pulumi:Stack devops-lab04-dev + + └─ aws:ec2:Instance devops-lab-vm created (15s) +Outputs: + + public_ip : "52.23.239.48" + + ssh_command: "ssh -i vockey.pem ubuntu@52.23.239.48" + +Resources: + + 1 created + 2 unchanged + +Duration: 19s +``` + +--- + +### 4. Public IP of Pulumi-created VM + +- **Public IP:** `52.23.239.48` + +--- + +### 5. SSH Connection to Pulumi-created VM + +```text +$ ssh -i vockey.pem ubuntu@52.23.239.48 +The authenticity of host '52.23.239.48 (52.23.239.48)' can't be established. +ED25519 key fingerprint is SHA256:eaXqPPGBnIH/fpt1A415YD81rIXEp9qZzwI4mhZAX+Q. +Are you sure you want to continue connecting (yes/no/[fingerprint])? yes +Welcome to Ubuntu 24.04.3 LTS (GNU/Linux 6.14.0-1018-aws x86_64) +ubuntu@ip-172-31-20-165:~$ +``` + +--- + +### 6. Code Differences (HCL vs Python) + +**Terraform HCL (declarative):** +```hcl +resource "aws_instance" "vm" { + ami = "ami-xxxxxx" + instance_type = "t2.micro" + vpc_security_group_ids = [aws_security_group.vm_sg.id] + key_name = var.key_name +} +``` + +**Pulumi Python (imperative):** +```python +vm = aws.ec2.Instance( + "devops-lab-vm", + instance_type="t2.micro", + vpc_security_group_ids=[sg.id], + ami="ami-0b6c6ebed2801a5cb", + key_name=key_name, + tags={"Name": "pulumi-devops-vm"} +) +``` +- Terraform uses a block structure where the “what” is described. +- Pulumi uses full Python; you can use loops, variables, functions, and conditionals. + +--- + +### 7. Comparison: Terraform vs Pulumi Experience + +**What was easier/harder than Terraform?** +- **Pulumi** was easier where custom logic or dynamic resource generation was needed, thanks to Python’s flexibility. +- **Terraform’s** declarative HCL was simpler for reading and building small or static environments. + +**How does the code differ?** +- Pulumi’s Python code allowed more reuse and dynamic logic, whereas Terraform’s HCL is closer to a static config file. + +**Which approach do you prefer and why?** +- For simple, repeatable cloud resources, I prefer Terraform for its simplicity. +--- + +### 8. Advantages of Pulumi Discovered + +- **Full Programming Language:** Can use loops, conditions, functions, and abstractions +- **Better IDE Support:** Type hints, autocomplete, native debugging +- **Native Testing:** Can write unit tests for infrastructure +- **Flexible Configuration:** Dynamic resource generation based on conditions +- **Secrets Encrypted by Default:** Better security than Terraform's plain text state +- **Familiar Language:** If you know Python, less new syntax to learn + + +### 9. Terraform vs Pulumi Comparison + +#### Ease of Learning +**Terraform** was easier to learn at first because its declarative HCL syntax is simple and focused—what you write closely maps to cloud resources with few abstractions. **Pulumi** requires understanding both the cloud provider’s constructs and general programming concepts, so there’s a steeper initial learning curve if you aren’t comfortable with Python. + +#### Code Readability +For small or static infrastructures, **Terraform**’s HCL is more readable because of its concise and “configuration-file” style. For larger, more complex, or dynamic setups, **Pulumi** becomes more readable to me, since Python allows logical grouping, comments, and abstraction. + +#### Debugging +**Pulumi** was somewhat easier to debug for me due to Python’s error outputs, stack traces, and the ability to use print statements or regular debugging tools. **Terraform** error messages are clear for straightforward mistakes, but harder to interpret for more complex logic or variable issues. + +#### Documentation +**Terraform** has more extensive, mature documentation and a huge variety of real-world examples. **Pulumi** has good docs and is catching up, but community content, Stack Overflow answers, and blog posts are much more plentiful for Terraform at the moment. + +#### Use Case +I would use **Terraform** for simple, standard infrastructure projects where configs are reused between teams and environments. **Pulumi** is best for advanced cases when I need to generate infrastructure dynamically, integrate with other Python libraries, or build highly automated/dev-programmable deployments. + +--- + +### 10. Lab 5 Preparation & Cleanup + +**VM for Lab 5:** + +- **Are you keeping your VM for Lab 5?** No + + I will recreate a cloud VM using **Terraform** for Lab 5. + +**Cleanup Status:** + +- All Pulumi-created AWS resources have been destroyed (`pulumi destroy`). +- Terraform resources were already removed in Task 2 (`terraform destroy`). +--- + +#### Terminal Output — Pulumi Cleanup + +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\pulumi> pulumi destroy +Enter your passphrase to unlock config/secrets + (set PULUMI_CONFIG_PASSPHRASE or PULUMI_CONFIG_PASSPHRASE_FILE to remember): +Enter your passphrase to unlock config/secrets +Previewing destroy (dev): + Type Name Plan + - pulumi:pulumi:Stack devops-lab04-dev delete + - ├─ aws:ec2:Instance devops-lab-vm delete + - └─ aws:ec2:SecurityGroup vm-sg delete +Outputs: + - public_ip : "52.23.239.48" + - ssh_command: "ssh -i labsuser.pem ubuntu@52.23.239.48" + +Resources: + - 3 to delete + +Do you want to perform this destroy? yes +Destroying (dev): + Type Name Status + - pulumi:pulumi:Stack devops-lab04-dev deleted (0.06s) + - ├─ aws:ec2:Instance devops-lab-vm deleted (62s) + - └─ aws:ec2:SecurityGroup vm-sg deleted (1s) +Outputs: + - public_ip : "52.23.239.48" + - ssh_command: "ssh -i labsuser.pem ubuntu@52.23.239.48" + +Resources: + - 3 deleted + +Duration: 1m6s +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\pulumi> +``` + +#### Terminal Output — Terraform Cleanup + +``` +Changes to Outputs: + - public_ip = "34.233.135.93" -> null + - ssh_command = "ssh ubuntu@34.233.135.93" -> null + +Do you really want to destroy all resources? + Terraform will destroy all your managed infrastructure, as shown above. + There is no undo. Only 'yes' will be accepted to confirm. + + Enter a value: yes + +aws_instance.vm: Destroying... [id=i-0122876d4c3947bed] +aws_instance.vm: Still destroying... [id=i-0122876d4c3947bed, 00m10s elapsed] +aws_instance.vm: Destruction complete after 1m2s +aws_security_group.vm_sg: Destroying... [id=sg-0e45f22278a7b1970] +aws_security_group.vm_sg: Destruction complete after 1s + +Destroy complete! Resources: 2 destroyed. +``` + +--- diff --git a/edge-api/.editorconfig b/edge-api/.editorconfig new file mode 100644 index 0000000000..a727df347a --- /dev/null +++ b/edge-api/.editorconfig @@ -0,0 +1,12 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = tab +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.yml] +indent_style = space diff --git a/edge-api/.gitignore b/edge-api/.gitignore new file mode 100644 index 0000000000..4138168d75 --- /dev/null +++ b/edge-api/.gitignore @@ -0,0 +1,167 @@ +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +\*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +\*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +\*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +\*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# parcel-bundler cache (https://parceljs.org/) + +.cache +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +.cache/ + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp +.cache + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.\* + +# wrangler project + +.dev.vars* +!.dev.vars.example +.env* +!.env.example +.wrangler/ diff --git a/edge-api/.prettierrc b/edge-api/.prettierrc new file mode 100644 index 0000000000..5c7b5d3c7a --- /dev/null +++ b/edge-api/.prettierrc @@ -0,0 +1,6 @@ +{ + "printWidth": 140, + "singleQuote": true, + "semi": true, + "useTabs": true +} diff --git a/edge-api/WORKERS.md b/edge-api/WORKERS.md new file mode 100644 index 0000000000..dc53f098c5 --- /dev/null +++ b/edge-api/WORKERS.md @@ -0,0 +1,314 @@ +# Lab 17 — Cloudflare Workers Edge Deployment + +## Task 1 — Cloudflare Setup + +### 1.1 Account and Project Creation +A new Cloudflare account was created, and a Workers project named `edge-api` was initialized using `npm create cloudflare@latest`. The project was configured with the "Hello World" TypeScript template. + +### 1.2 CLI Authentication +The Wrangler CLI was authenticated by running `npx wrangler login`. Verification was successful, as confirmed by the output of `npx wrangler whoami`: + +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler whoami + + ⛅️ wrangler 4.90.0 +─────────────────── +Getting User settings... +👋 You are logged in with an OAuth Token, associated with the email kostikova658@gmail.com. +┌──────────────────────────────────┬──────────────────────────────────┐ +│ Account Name │ Account ID │ +├──────────────────────────────────┼──────────────────────────────────┤ +│ Kostikova658@gmail.com's Account │ 94f7d5ad139a9ee913caf0db9e3f2b1d │ +└──────────────────────────────────┴──────────────────────────────────┘ +``` + +### 1.3 Platform Concepts + +- **Workers Runtime:** A lightweight JavaScript/Wasm serverless environment based on the V8 engine. It runs code at the edge without containers or VMs, enabling extremely fast cold starts. +- **`workers.dev` URLs:** A free subdomain provided by Cloudflare for every Worker, allowing instant public access without needing a custom domain. The format is `my-worker.my-subdomain.workers.dev`. +- **Bindings:** A mechanism to connect a Worker to resources like environment variables (`vars`), encrypted secrets (`secrets`), and key-value storage (`KV namespaces`). This is how configuration and state are managed. + +--- + +## Task 2 — Build and Deploy a Worker API + +### 2.1 Implemented Routes +A simple router was implemented in `src/index.ts` to handle requests to three distinct endpoints: +- `GET /`: A welcome message. +- `GET /health`: A health check endpoint returning `OK` with status 200. +- `GET /info`: An endpoint returning basic deployment metadata as a JSON object. + +### 2.2 Local and Remote Deployment + +**Local Verification:** +The Worker was tested locally using `npx wrangler dev`. The terminal output confirms that all implemented routes responded correctly with a `200 OK` status. + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler dev +... +⎔ Starting local server... +[wrangler:info] Ready on http://127.0.0.1:8787 +[wrangler:info] GET / 200 OK (7ms) +[wrangler:info] GET /favicon.ico 404 Not Found (3ms) +[wrangler:info] GET /health 200 OK (3ms) +[wrangler:info] GET /info 200 OK (4ms) +``` + +**Remote Deployment:** +The Worker was then deployed to the Cloudflare global network using `npx wrangler deploy`. + +- **Public URL:** `https://edge-api.kostikova658.workers.dev` + +**Deployment Output:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler deploy + + ⛅️ wrangler 4.90.0 +─────────────────── +Total Upload: 0.82 KiB / gzip: 0.42 KiB +Worker Startup Time: 4 ms +Uploaded edge-api (7.98 sec) +Deployed edge-api triggers (5.90 sec) + https://edge-api.kostikova658.workers.dev +Current Version ID: 6de8c48b-0422-4f07-91fb-10787bb9eab6 +``` + +### 2.3 Version Control +All changes were committed to Git with the message `feat: implement initial API routes for v1.0.0`, establishing a baseline for future deployments. + +--- + +## Task 3 — Global Edge Behavior + +### 3.1 Edge Metadata Endpoint +A new endpoint `GET /edge` was added to return metadata from the incoming request context (`request.cf`). This object provides information about the Cloudflare data center that handled the request. + +**Code added to `src/index.ts`:** +```typescript +// Edge metadata endpoint +if (url.pathname === '/edge') { + const edgeMetadata = { + colo: request.cf?.colo, + country: request.cf?.country, + city: request.cf?.city, + httpProtocol: request.cf?.httpProtocol, + tlsVersion: request.cf?.tlsVersion, + asn: request.cf?.asn, + }; + return new Response(JSON.stringify(edgeMetadata, null, 2), { + headers: { 'Content-Type': 'application/json' }, + }); +} +``` + +### 3.2 Public Edge Execution Verification +After deploying the new version (`f78bbc5e-b847-44d0-9780-d28241854522`), the `/edge` endpoint was called. The response confirms that the code is running on Cloudflare's global network and has access to request-specific metadata. The request was routed through the Frankfurt data center. + +**JSON Response from `https://edge-api.kostikova658.workers.dev/edge`:** +```json +{ + "colo": "IAD", + "country": "DE", + "city": "Frankfurt am Main", + "httpProtocol": "HTTP/2", + "tlsVersion": "TLSv1.3", + "asn": 210644 +} +``` + +### 3.3 Global Distribution Explained +Cloudflare Workers automatically deploys code to its entire global network of data centers (over 300 cities). When a user makes a request, Cloudflare's Anycast network routes it to the nearest data center. This is fundamentally different from traditional cloud platforms (VMs, PaaS, Kubernetes) where you must manually select specific regions (e.g., `us-east-1`, `eu-west-2`) for deployment. With Workers, there is no "deploy to 3 regions" step because it deploys to *all* regions by default, minimizing latency for users worldwide. + +### 3.4 Routing Concepts + +- **`workers.dev`:** A free, managed subdomain provided by Cloudflare for instant public access to a Worker. It's ideal for development, testing, and simple APIs without needing your own domain. +- **Routes:** A mapping that connects a specific path on a *custom domain* (e.g., `api.mycompany.com/v1/*`) to a specific Worker. This is used for production traffic on your own domains. +- **Custom Domains:** Your own registered domain (e.g., `mycompany.com`) that you add to your Cloudflare account. You can then create Routes to trigger Workers from traffic to that domain. +--- + +## Task 4 — Configuration, Secrets & Persistence + +### 4.1 Environment Variables +A plaintext environment variable `API_VERSION` was defined in `wrangler.jsonc` and used in the `/info` endpoint. + +**`wrangler.jsonc` configuration:** +```jsonc +"vars": { + "API_VERSION": "v1.1.0" +} +``` +**Why not for secrets:** Plaintext variables in `wrangler.jsonc` are committed to version control, making them visible to anyone with repository access. This is a major security risk for sensitive data like API keys or passwords. + +### 4.2 Secrets +Two secrets, `API_KEY` (value: `secret_key1`) and `ADMIN_EMAIL` (value: `admin@example.com`), were created using `npx wrangler secret put`. They are accessible via the `env` object in the Worker but their values are not stored in Git. The `/config` endpoint confirms they are loaded without exposing the `API_KEY` value itself. + +**Verification via `/config` endpoint:** +```json +{ + "apiVersion": "v1.1.0", + "adminEmail": "admin@example.com", + "apiKeyLoaded": "true" +} +``` + +### 4.3 Persistence with Workers KV +A Workers KV namespace named `EDGE_KV` was created using `npx wrangler kv namespace create EDGE_KV` and bound to the Worker in `wrangler.jsonc`. API endpoints `POST /kv/:key` and `GET /kv/:key` were implemented to store and retrieve data. The routing logic was updated to support hyphens in keys. + +**`wrangler.jsonc` binding:** +```jsonc +"kv_namespaces": [ + { + "binding": "EDGE_KV", + "id": "1600409be4814f9aaf1a48fafbb7b263" + } +] +``` + +**Persistence Verification:** +A value was stored and successfully retrieved using PowerShell, confirming the KV binding works. The deployment ID for this version is `e8e167c6-33f9-4e90-bc87-cf0b61655969`. +```powershell +# 1. Store a value +> Invoke-WebRequest -Uri "https://edge-api.kostikova658.workers.dev/kv/test-key" -Method POST -Body "hello from the edge" + +StatusCode : 201 +StatusDescription : Created +Content : Stored value for key: test-key + +# 2. Retrieve the value +> Invoke-WebRequest -Uri "https://edge-api.kostikova658.workers.dev/kv/test-key" + +StatusCode : 200 +StatusDescription : OK +Content : hello from the edge +``` +The value persisted across deployments, as it is stored in Cloudflare's distributed KV store, not in the Worker's ephemeral memory. + +--- + +## Task 5 — Observability & Operations + +### 5.1 Inspecting Logs +A `console.log()` statement was added to the `/health` endpoint to demonstrate logging. The `npx wrangler tail` command was used to view live logs from the deployed Worker. + +**Live Log Output:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course\edge-api> npx wrangler tail +... +Connected to edge-api, waiting for logs... +GET https://edge-api.kostikova658.workers.dev/health - Ok @ 09.05.2026, 22:37:18 + (log) Health check performed at 2026-05-09T19:37:18.373Z +GET https://edge-api.kostikova658.workers.dev/health - Ok @ 09.05.2026, 22:37:28 + (log) Health check performed at 2026-05-09T19:37:28.493Z +``` + +### 5.2 Inspecting Metrics +The Cloudflare dashboard provides real-time metrics for the Worker. I reviewed the **Requests** metric on the "Metrics" tab, which shows the total number of invocations over time (13 requests in the last 24 hours). This is a key indicator of traffic volume and application usage. I also observed the **CPU Time** (0.62ms average) and **Request Duration** (0.91ms average), which confirm the high performance of the Worker. + +![Worker Metrics](./edge-api/screenshots/metrics.png) + +### 5.3 Managing Deployments +Cloudflare Workers maintains a history of all deployments, which can be managed via the dashboard or the Wrangler CLI. + +- **Deployment History:** The `npx wrangler deployments list` command was used to view the history of all deployed versions. The active version before the rollback was `33300607...`. + +- **Rollback via CLI:** A rollback to a previous, stable version (`6de8c48b...`) was performed using the command line. This provides a fast and scriptable way to revert changes in production. + +**Rollback Command Output:** +```powershell +# 1. List deployments to find the target version ID +> npx wrangler deployments list +... +Created: 2026-05-09T19:36:54.696Z +... +Version(s): (100%) 33300607-68c9-49b0-94f2-055d67a6ca5f +... +Created: 2026-05-09T19:15:09.002Z +... +Version(s): (100%) 6de8c48b-0422-4f07-91fb-10787bb9eab6 +... + +# 2. Execute the rollback +> npx wrangler rollback 6de8c48b-0422-4f07-91fb-10787bb9eab6 + + ⛅️ wrangler 4.90.0 +─────────────────── +... +√ Are you sure you want to deploy this Worker Version to 100% of traffic? ... yes +Performing rollback... +│ +╰ SUCCESS Worker Version 6de8c48b-0422-4f07-91fb-10787bb9eab6 has been deployed to 100% of traffic. + +Current Version ID: 6de8c48b-0422-4f07-91fb-10787bb9eab6 +``` +The rollback was instantly applied, and the previously active version (`33300607...`) was replaced by the target version (`6de8c48b...`) in production. + +![Deployment History](./edge-api/screenshots/deployments.png) +![Deployment History](./edge-api/screenshots/history.png) + +After rollback: +![Deployment History](./edge-api/screenshots/rollback.png) +--- + +## Task 6 — Documentation & Comparison + +### 6.1 Deployment Summary + +- **Worker URL:** `https://edge-api.kostikova658.workers.dev` +- **Main Routes:** + - `GET /`: Welcome message + - `GET /health`: Health check + - `GET /info`: Basic deployment info + - `GET /edge`: Edge location metadata + - `GET /config`: Loaded configuration and secrets + - `GET /kv/:key`, `POST /kv/:key`: KV storage operations +- **Configuration Used:** + - **Vars:** `API_VERSION` + - **Secrets:** `API_KEY`, `ADMIN_EMAIL` + - **KV Namespace:** `EDGE_KV` + +### 6.2 Evidence +*(All evidence is detailed in previous tasks)* +- **Cloudflare Dashboard:** Screenshot of metrics is in Task 5 +- **/edge JSON Response:** Included in Task 3 +- **Log/Metrics Screenshot:** Live log output is in Task 5 + +### 6.3 Kubernetes vs Cloudflare Workers Comparison + +| Aspect | Kubernetes | Cloudflare Workers | +| ----------------------- | ------------------------------------------------ | ------------------------------------------------ | +| **Setup complexity** | **High:** Requires cluster setup, networking, YAML | **Low:** `npm create`, `wrangler login` | +| **Deployment speed** | **Slow:** (Minutes) Image build, push, pod pull | **Very Fast:** (Seconds) `wrangler deploy` | +| **Global distribution** | **Manual:** Requires multi-cluster/region setup | **Automatic:** Deploys to 300+ cities by default | +| **Cost (for small apps)** | **High:** ($50+/mo) Nodes, Load Balancers | **Very Low:** Generous free tier | +| **State/persistence** | **Flexible:** PVCs, `emptyDir`, external DBs | **Limited:** Workers KV, Durable Objects | +| **Control/flexibility** | **Total Control:** Any language, OS, binary | **Constrained:** JS/Wasm runtime, API limits | +| **Best use case** | Complex microservices, stateful apps, enterprise | APIs, webhooks, auth, static site middleware | + +### 6.4 When to Use Each + +**Scenarios favoring Kubernetes:** +- You have a large, complex application with many microservices. +- You need full control over the operating system, networking, and specific binaries. +- Your application is stateful and requires complex storage solutions like databases or message queues running in the cluster. +- You are building a platform for other developers in your company. + +**Scenarios favoring Cloudflare Workers:** +- You need to build a fast, globally distributed API with minimal latency. +- Your application is stateless or has simple state needs (key-value). +- You have a small team and want to minimize infrastructure management overhead. +- You are building middleware for a static site, handling authentication, or running A/B tests at the edge. + +**My Recommendation:** +For startups, personal projects, and API-driven services where global low latency is critical, **Cloudflare Workers** is a superior starting point due to its simplicity and cost-effectiveness. For large enterprises with complex, stateful systems and dedicated platform teams, **Kubernetes** remains the standard for its power and flexibility. + +### 6.5 Reflection + +- **What felt easier than Kubernetes?** + Almost everything. The setup (`npm create`), deployment (`wrangler deploy`), secrets management, and instant global distribution were orders of magnitude simpler than managing Kubernetes manifests, clusters, and Ingress controllers. + +- **What felt more constrained?** + The runtime environment. In Kubernetes, I can run any Docker container (Python, Go, Java, etc.). With Workers, I am limited to JavaScript/TypeScript and Wasm. The persistence model (KV store) is also much simpler and less flexible than the variety of storage options in Kubernetes (PVCs, etc.). + +- **What changed because Workers is not a Docker host?** + The entire development mindset shifted. Instead of packaging an OS and application into a Docker image, I wrote code directly against the Cloudflare runtime API. There was no `Dockerfile`, no `docker build`, and no concern for the underlying operating system. The focus was purely on the application logic. + diff --git a/edge-api/package-lock.json b/edge-api/package-lock.json new file mode 100644 index 0000000000..7adee25cf0 --- /dev/null +++ b/edge-api/package-lock.json @@ -0,0 +1,2913 @@ +{ + "name": "edge-api", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "edge-api", + "version": "0.0.0", + "devDependencies": { + "@cloudflare/vitest-pool-workers": "^0.12.4", + "@types/node": "^25.6.2", + "typescript": "^5.5.2", + "vitest": "~3.2.0", + "wrangler": "^4.90.0" + } + }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz", + "integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/vitest-pool-workers": { + "version": "0.12.21", + "resolved": "https://registry.npmjs.org/@cloudflare/vitest-pool-workers/-/vitest-pool-workers-0.12.21.tgz", + "integrity": "sha512-xqvqVR+qAhekXWaTNY36UtFFmHrz13yGUoWVGOu6LDC2ABiQqI1E1lQ3eUZY8KVB+1FXY/mP5dB6oD07XUGnPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cjs-module-lexer": "^1.2.3", + "esbuild": "0.27.3", + "miniflare": "4.20260310.0", + "wrangler": "4.72.0" + }, + "peerDependencies": { + "@vitest/runner": "2.0.x - 3.2.x", + "@vitest/snapshot": "2.0.x - 3.2.x", + "vitest": "2.0.x - 3.2.x" + } + }, + "node_modules/@cloudflare/vitest-pool-workers/node_modules/@cloudflare/kv-asset-handler": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.4.2.tgz", + "integrity": "sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@cloudflare/vitest-pool-workers/node_modules/@cloudflare/unenv-preset": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.15.0.tgz", + "integrity": "sha512-EGYmJaGZKWl+X8tXxcnx4v2bOZSjQeNI5dWFeXivgX9+YCT69AkzHHwlNbVpqtEUTbew8eQurpyOpeN8fg00nw==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": "1.20260301.1 || ~1.20260302.1 || ~1.20260303.1 || ~1.20260304.1 || >1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/vitest-pool-workers/node_modules/wrangler": { + "version": "4.72.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.72.0.tgz", + "integrity": "sha512-bKkb8150JGzJZJWiNB2nu/33smVfawmfYiecA6rW4XH7xS23/jqMbgpdelM34W/7a1IhR66qeQGVqTRXROtAZg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.4.2", + "@cloudflare/unenv-preset": "2.15.0", + "blake3-wasm": "2.1.5", + "esbuild": "0.27.3", + "miniflare": "4.20260310.0", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20260310.1" + }, + "bin": { + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=20.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^4.20260310.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260310.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260310.1.tgz", + "integrity": "sha512-hF2VpoWaMb1fiGCQJqCY6M8I+2QQqjkyY4LiDYdTL5D/w6C1l5v1zhc0/jrjdD1DXfpJtpcSMSmEPjHse4p9Ig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260310.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260310.1.tgz", + "integrity": "sha512-h/Vl3XrYYPI6yFDE27XO1QPq/1G1lKIM8tzZGIWYpntK3IN5XtH3Ee/sLaegpJ49aIJoqhF2mVAZ6Yw+Vk2gJw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260310.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260310.1.tgz", + "integrity": "sha512-XzQ0GZ8G5P4d74bQYOIP2Su4CLdNPpYidrInaSOuSxMw+HamsHaFrjVsrV2mPy/yk2hi6SY2yMbgKFK9YjA7vw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260310.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260310.1.tgz", + "integrity": "sha512-sxv4CxnN4ZR0uQGTFVGa0V4KTqwdej/czpIc5tYS86G8FQQoGIBiAIs2VvU7b8EROPcandxYHDBPTb+D9HIMPw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260310.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260310.1.tgz", + "integrity": "sha512-+1ZTViWKJypLfgH/luAHCqkent0DEBjAjvO40iAhOMHRLYP/SPphLvr4Jpi6lb+sIocS8Q1QZL4uM5Etg1Wskg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", + "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz", + "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz", + "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz", + "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz", + "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz", + "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz", + "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz", + "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz", + "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz", + "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz", + "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz", + "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz", + "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz", + "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz", + "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz", + "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz", + "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz", + "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz", + "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz", + "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz", + "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz", + "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz", + "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz", + "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz", + "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz", + "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz", + "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.3.tgz", + "integrity": "sha512-x35CNW/ANXG3hE/EZpRU8MXX1JDN86hBb2wMGAtltkz7pc6cxgjpy1OMMfDosOQ+2hWqIkag/fGok1Yady9nGw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.3.tgz", + "integrity": "sha512-xw3xtkDApIOGayehp2+Rz4zimfkaX65r4t47iy+ymQB2G4iJCBBfj0ogVg5jpvjpn8UWn/+q9tprxleYeNp3Hw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.3.tgz", + "integrity": "sha512-vo6Y5Qfpx7/5EaamIwi0WqW2+zfiusVihKatLvtN1VFVy3D13uERk/6gZLU1UiHRL6fDXqj/ELIeVRGnvcTE1g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.3.tgz", + "integrity": "sha512-D+0QGcZhBzTN82weOnsSlY7V7+RMmPuF1CkbxyMAGE8+ZHeUjyb76ZiWmBlCu//AQQONvxcqRbwZTajZKqjuOw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.3.tgz", + "integrity": "sha512-6HnvHCT7fDyj6R0Ph7A6x8dQS/S38MClRWeDLqc0MdfWkxjiu1HSDYrdPhqSILzjTIC/pnXbbJbo+ft+gy/9hQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.3.tgz", + "integrity": "sha512-KHLgC3WKlUYW3ShFKnnosZDOJ0xjg9zp7au3sIm2bs/tGBeC2ipmvRh/N7JKi0t9Ue20C0dpEshi8WUubg+cnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.3.tgz", + "integrity": "sha512-DV6fJoxEYWJOvaZIsok7KrYl0tPvga5OZ2yvKHNNYyk/2roMLqQAbGhr78EQ5YhHpnhLKJD3S1WFusAkmUuV5g==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.3.tgz", + "integrity": "sha512-mQKoJAzvuOs6F+TZybQO4GOTSMUu7v0WdxEk24krQ/uUxXoPTtHjuaUuPmFhtBcM4K0ons8nrE3JyhTuCFtT/w==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.3.tgz", + "integrity": "sha512-Whjj2qoiJ6+OOJMGptTYazaJvjOJm+iKHpXQM1P3LzGjt7Ff++Tp7nH4N8J/BUA7R9IHfDyx4DJIflifwnbmIA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.3.tgz", + "integrity": "sha512-4YTNHKqGng5+yiZt3mg77nmyuCfmNfX4fPmyUapBcIk+BdwSwmCWGXOUxhXbBEkFHtoN5boLj/5NON+u5QC9tg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.3.tgz", + "integrity": "sha512-SU3kNlhkpI4UqlUc2VXPGK9o886ZsSeGfMAX2ba2b8DKmMXq4AL7KUrkSWVbb7koVqx41Yczx6dx5PNargIrEA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.3.tgz", + "integrity": "sha512-6lDLl5h4TXpB1mTf2rQWnAk/LcXrx9vBfu/DT5TIPhvMhRWaZ5MxkIc8u4lJAmBo6klTe1ywXIUHFjylW505sg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.3.tgz", + "integrity": "sha512-BMo8bOw8evlup/8G+cj5xWtPyp93xPdyoSN16Zy90Q2QZ0ZYRhCt6ZJSwbrRzG9HApFabjwj2p25TUPDWrhzqQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.3.tgz", + "integrity": "sha512-E0L8X1dZN1/Rph+5VPF6Xj2G7JJvMACVXtamTJIDrVI44Y3K+G8gQaMEAavbqCGTa16InptiVrX6eM6pmJ+7qA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.3.tgz", + "integrity": "sha512-oZJ/WHaVfHUiRAtmTAeo3DcevNsVvH8mbvodjZy7D5QKvCefO371SiKRpxoDcCxB3PTRTLayWBkvmDQKTcX/sw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.3.tgz", + "integrity": "sha512-Dhbyh7j9FybM3YaTgaHmVALwA8AkUwTPccyCQ79TG9AJUsMQqgN1DDEZNr4+QUfwiWvLDumW5vdwzoeUF+TNxQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.3.tgz", + "integrity": "sha512-cJd1X5XhHHlltkaypz1UcWLA8AcoIi1aWhsvaWDskD1oz2eKCypnqvTQ8ykMNI0RSmm7NkTdSqSSD7zM0xa6Ig==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.3.tgz", + "integrity": "sha512-DAZDBHQfG2oQuhY7mc6I3/qB4LU2fQCjRvxbDwd/Jdvb9fypP4IJ4qmtu6lNjes6B531AI8cg1aKC2di97bUxA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.3.tgz", + "integrity": "sha512-cRxsE8c13mZOh3vP+wLDxpQBRrOHDIGOWyDL93Sy0Ga8y515fBcC2pjUfFwUe5T7tqvTvWbCpg1URM/AXdWIXA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.3.tgz", + "integrity": "sha512-QaWcIgRxqEdQdhJqW4DJctsH6HCmo5vHxY0krHSX4jMtOqfzC+dqDGuHM87bu4H8JBeibWx7jFz+h6/4C8wA5Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.3.tgz", + "integrity": "sha512-AaXwSvUi3QIPtroAUw1t5yHGIyqKEXwH54WUocFolZhpGDruJcs8c+xPNDRn4XiQsS7MEwnYsHW2l0MBLDMkWg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.3.tgz", + "integrity": "sha512-65LAKM/bAWDqKNEelHlcHvm2V+Vfb8C6INFxQXRHCvaVN1rJfwr4NvdP4FyzUaLqWfaCGaadf6UbTm8xJeYfEg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.3.tgz", + "integrity": "sha512-EEM2gyhBF5MFnI6vMKdX1LAosE627RGBzIoGMdLloPZkXrUN0Ckqgr2Qi8+J3zip/8NVVro3/FjB+tjhZUgUHA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.3.tgz", + "integrity": "sha512-E5Eb5H/DpxaoXH++Qkv28RcUJboMopmdDUALBczvHMf7hNIxaDZqwY5lK12UK1BHacSmvupoEWGu+n993Z0y1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.3.tgz", + "integrity": "sha512-hPt/bgL5cE+Qp+/TPHBqptcAgPzgj46mPcg/16zNUmbQk0j+mOEQV/+Lqu8QRtDV3Ek95Q6FeFITpuhl6OTsAA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.15.tgz", + "integrity": "sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.6.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.2.tgz", + "integrity": "sha512-sokuT28dxf9JT5Kady1fsXOvI4HVpjZa95NKT5y9PNTIrs2AsobR4GFAA90ZG8M+nxVRLysCXsVj6eGC7Vbrlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.19.0" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz", + "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.3", + "@esbuild/android-arm": "0.27.3", + "@esbuild/android-arm64": "0.27.3", + "@esbuild/android-x64": "0.27.3", + "@esbuild/darwin-arm64": "0.27.3", + "@esbuild/darwin-x64": "0.27.3", + "@esbuild/freebsd-arm64": "0.27.3", + "@esbuild/freebsd-x64": "0.27.3", + "@esbuild/linux-arm": "0.27.3", + "@esbuild/linux-arm64": "0.27.3", + "@esbuild/linux-ia32": "0.27.3", + "@esbuild/linux-loong64": "0.27.3", + "@esbuild/linux-mips64el": "0.27.3", + "@esbuild/linux-ppc64": "0.27.3", + "@esbuild/linux-riscv64": "0.27.3", + "@esbuild/linux-s390x": "0.27.3", + "@esbuild/linux-x64": "0.27.3", + "@esbuild/netbsd-arm64": "0.27.3", + "@esbuild/netbsd-x64": "0.27.3", + "@esbuild/openbsd-arm64": "0.27.3", + "@esbuild/openbsd-x64": "0.27.3", + "@esbuild/openharmony-arm64": "0.27.3", + "@esbuild/sunos-x64": "0.27.3", + "@esbuild/win32-arm64": "0.27.3", + "@esbuild/win32-ia32": "0.27.3", + "@esbuild/win32-x64": "0.27.3" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/miniflare": { + "version": "4.20260310.0", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260310.0.tgz", + "integrity": "sha512-uC5vNPenFpDSj5aUU3wGSABG6UUqMr+Xs1m4AkCrTHo37F4Z6xcQw5BXqViTfPDVT/zcYH1UgTVoXhr1l6ZMXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "^0.34.5", + "undici": "7.18.2", + "workerd": "1.20260310.1", + "ws": "8.18.0", + "youch": "4.1.0-beta.10" + }, + "bin": { + "miniflare": "bootstrap.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.12", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", + "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.14", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.14.tgz", + "integrity": "sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.60.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.3.tgz", + "integrity": "sha512-pAQK9HalE84QSm4Po3EmWIZPd3FnjkShVkiMlz1iligWYkWQ7wHYd1PF/T7QZ5TVSD6uSTon5gBVMSM4JfBV+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.60.3", + "@rollup/rollup-android-arm64": "4.60.3", + "@rollup/rollup-darwin-arm64": "4.60.3", + "@rollup/rollup-darwin-x64": "4.60.3", + "@rollup/rollup-freebsd-arm64": "4.60.3", + "@rollup/rollup-freebsd-x64": "4.60.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.60.3", + "@rollup/rollup-linux-arm-musleabihf": "4.60.3", + "@rollup/rollup-linux-arm64-gnu": "4.60.3", + "@rollup/rollup-linux-arm64-musl": "4.60.3", + "@rollup/rollup-linux-loong64-gnu": "4.60.3", + "@rollup/rollup-linux-loong64-musl": "4.60.3", + "@rollup/rollup-linux-ppc64-gnu": "4.60.3", + "@rollup/rollup-linux-ppc64-musl": "4.60.3", + "@rollup/rollup-linux-riscv64-gnu": "4.60.3", + "@rollup/rollup-linux-riscv64-musl": "4.60.3", + "@rollup/rollup-linux-s390x-gnu": "4.60.3", + "@rollup/rollup-linux-x64-gnu": "4.60.3", + "@rollup/rollup-linux-x64-musl": "4.60.3", + "@rollup/rollup-openbsd-x64": "4.60.3", + "@rollup/rollup-openharmony-arm64": "4.60.3", + "@rollup/rollup-win32-arm64-msvc": "4.60.3", + "@rollup/rollup-win32-ia32-msvc": "4.60.3", + "@rollup/rollup-win32-x64-gnu": "4.60.3", + "@rollup/rollup-win32-x64-msvc": "4.60.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/rollup/node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", + "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.18.2.tgz", + "integrity": "sha512-y+8YjDFzWdQlSE9N5nzKMT3g4a5UBX1HKowfdXh0uvAnTaqqwqB92Jt4UXBAeKekDs5IaDKyJFR4X1gYVCgXcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "7.19.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz", + "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", + "dev": true, + "license": "MIT" + }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3" + } + }, + "node_modules/vite": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.3.tgz", + "integrity": "sha512-/4XH147Ui7OGTjg3HbdWe5arnZQSbfuRzdr9Ec7TQi5I7R+ir0Rlc9GIvD4v0XZurELqA035KVXJXpR61xhiTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/workerd": { + "version": "1.20260310.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260310.1.tgz", + "integrity": "sha512-yawXhypXXHtArikJj15HOMknNGikpBbSg2ZDe6lddUbqZnJXuCVSkgc/0ArUeVMG1jbbGvpst+REFtKwILvRTQ==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260310.1", + "@cloudflare/workerd-darwin-arm64": "1.20260310.1", + "@cloudflare/workerd-linux-64": "1.20260310.1", + "@cloudflare/workerd-linux-arm64": "1.20260310.1", + "@cloudflare/workerd-windows-64": "1.20260310.1" + } + }, + "node_modules/wrangler": { + "version": "4.90.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.90.0.tgz", + "integrity": "sha512-bmNIykl59TfCUn5xQgU7IWylSsPx3LQaPLMSAq2VQHt89CBrcj9qXQ0eYfjBCWA5XTBVgten391evt7xxtXwcA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.1", + "blake3-wasm": "2.1.5", + "esbuild": "0.27.3", + "miniflare": "4.20260507.1", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20260507.1" + }, + "bin": { + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^4.20260507.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260507.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260507.1.tgz", + "integrity": "sha512-S85aMwcaPJUjKWDiG6iMMnioKWtPLACa6m0j/EhHR1GYfVpnxb974cBc6d25L+sf7jHWHJI2u5hGp0UTJ7MtXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260507.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260507.1.tgz", + "integrity": "sha512-GMEBu8Zp9Q97HLnf7bWJN4KjWpN5MxpeqdvHjBGWNl8UYprJI0k+Jkp89+Wh5S8vIon+HoVbDfOzPa7VwgL6Eg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260507.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260507.1.tgz", + "integrity": "sha512-QlrKEBdgA3uVc0Ok0Q3+0/CW0CTjgj5ySir1i1YY5FXVv0X6GpwtnB5umjunjF2MFprss+L+iFGZzxcSvMC1nA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260507.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260507.1.tgz", + "integrity": "sha512-eGbbupEtK2nh9V9Dhcx3vv3GTKeXqSVNgAEYVCCN0NGS9tl9HbMoHRX/4JL181FKXROMigWBCQVL//qPhsAzBQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260507.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260507.1.tgz", + "integrity": "sha512-dmClJ/E0BAcuDetQIZFqbeAXejWrG5pysGRMQ6T83Y0IW/7IAamY2zFEkAJ10I5xwZsdHuYsZtzlOxpEXpJs7A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/miniflare": { + "version": "4.20260507.1", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260507.1.tgz", + "integrity": "sha512-PSXBiLExTdZ4UGO/raKCHQauUpYL7F880ZRB7j0+78Rv8h7TsdN2E/iEDK9sK2Y+SPQ5wJSeAa+rDeVKoZZoEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "^0.34.5", + "undici": "7.24.8", + "workerd": "1.20260507.1", + "ws": "8.18.0", + "youch": "4.1.0-beta.10" + }, + "bin": { + "miniflare": "bootstrap.js" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/wrangler/node_modules/undici": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.24.8.tgz", + "integrity": "sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/wrangler/node_modules/workerd": { + "version": "1.20260507.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260507.1.tgz", + "integrity": "sha512-z7JhsFSe6+X1b5fUHaVpo15VM1IRMJiLofEkq8iKdCo+Veqc+FUg5lIsuz8NwePxuSKrXtO4ZQpGkQLbPVXFhg==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260507.1", + "@cloudflare/workerd-darwin-arm64": "1.20260507.1", + "@cloudflare/workerd-linux-64": "1.20260507.1", + "@cloudflare/workerd-linux-arm64": "1.20260507.1", + "@cloudflare/workerd-windows-64": "1.20260507.1" + } + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + } + } +} diff --git a/edge-api/package.json b/edge-api/package.json new file mode 100644 index 0000000000..4452b7a7f3 --- /dev/null +++ b/edge-api/package.json @@ -0,0 +1,19 @@ +{ + "name": "edge-api", + "version": "0.0.0", + "private": true, + "scripts": { + "deploy": "wrangler deploy", + "dev": "wrangler dev", + "start": "wrangler dev", + "test": "vitest", + "cf-typegen": "wrangler types" + }, + "devDependencies": { + "@cloudflare/vitest-pool-workers": "^0.12.4", + "@types/node": "^25.6.2", + "typescript": "^5.5.2", + "vitest": "~3.2.0", + "wrangler": "^4.90.0" + } +} \ No newline at end of file diff --git a/edge-api/screenshots/deployments.png b/edge-api/screenshots/deployments.png new file mode 100644 index 0000000000..53be75399e Binary files /dev/null and b/edge-api/screenshots/deployments.png differ diff --git a/edge-api/screenshots/history.png b/edge-api/screenshots/history.png new file mode 100644 index 0000000000..6c29f69756 Binary files /dev/null and b/edge-api/screenshots/history.png differ diff --git a/edge-api/screenshots/metrics.png b/edge-api/screenshots/metrics.png new file mode 100644 index 0000000000..a699e8d2ba Binary files /dev/null and b/edge-api/screenshots/metrics.png differ diff --git a/edge-api/screenshots/rollback.png b/edge-api/screenshots/rollback.png new file mode 100644 index 0000000000..3136102228 Binary files /dev/null and b/edge-api/screenshots/rollback.png differ diff --git a/edge-api/src/index.ts b/edge-api/src/index.ts new file mode 100644 index 0000000000..c286520683 --- /dev/null +++ b/edge-api/src/index.ts @@ -0,0 +1,78 @@ +export interface Env { + API_VERSION: string; + API_KEY: string; + ADMIN_EMAIL: string; + EDGE_KV: KVNamespace; +} + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const url = new URL(request.url); + + // Root endpoint + if (url.pathname === '/') { + return new Response('Welcome to the Edge API!', { headers: { 'Content-Type': 'text/plain' } }); + } + + // Health check endpoint + if (url.pathname === '/health') { + console.log(`Health check performed at ${new Date().toISOString()}`); + return new Response('OK', { status: 200 }); + } + + // Deployment info endpoint + if (url.pathname === '/info') { + const deploymentInfo = { + deploymentId: env.API_VERSION, + timestamp: new Date().toISOString(), + region: 'Global Edge', + }; + return new Response(JSON.stringify(deploymentInfo, null, 2), { headers: { 'Content-Type': 'application/json' } }); + } + + // Edge metadata endpoint + if (url.pathname === '/edge') { + const edgeMetadata = { + colo: request.cf?.colo, + country: request.cf?.country, + city: request.cf?.city, + httpProtocol: request.cf?.httpProtocol, + tlsVersion: request.cf?.tlsVersion, + asn: request.cf?.asn, + }; + return new Response(JSON.stringify(edgeMetadata, null, 2), { headers: { 'Content-Type': 'application/json' } }); + } + + // Config and secrets endpoint + if (url.pathname === '/config') { + const config = { + apiVersion: env.API_VERSION, + adminEmail: env.ADMIN_EMAIL, + apiKeyLoaded: env.API_KEY ? 'true' : 'false', // Не показываем сам ключ! + }; + return new Response(JSON.stringify(config, null, 2), { headers: { 'Content-Type': 'application/json' } }); + } + + // KV storage endpoint + const kvMatch = url.pathname.match(/^\/kv\/([\w-]+)$/); + if (kvMatch) { + const key = kvMatch[1]; + if (request.method === 'POST') { + const value = await request.text(); + await env.EDGE_KV.put(key, value); + return new Response(`Stored value for key: ${key}`, { status: 201 }); + } + if (request.method === 'GET') { + const value = await env.EDGE_KV.get(key); + if (value === null) { + return new Response('Not Found', { status: 404 }); + } + return new Response(value, { headers: { 'Content-Type': 'text/plain' } }); + } + return new Response('Method Not Allowed', { status: 405 }); + } + + // 404 Not Found for other paths + return new Response('Not Found', { status: 404 }); + }, +}; \ No newline at end of file diff --git a/edge-api/test/env.d.ts b/edge-api/test/env.d.ts new file mode 100644 index 0000000000..67b3610dbc --- /dev/null +++ b/edge-api/test/env.d.ts @@ -0,0 +1,3 @@ +declare module "cloudflare:test" { + interface ProvidedEnv extends Env {} +} diff --git a/edge-api/test/index.spec.ts b/edge-api/test/index.spec.ts new file mode 100644 index 0000000000..81abe3d31e --- /dev/null +++ b/edge-api/test/index.spec.ts @@ -0,0 +1,29 @@ +import { + env, + createExecutionContext, + waitOnExecutionContext, + SELF, +} from "cloudflare:test"; +import { describe, it, expect } from "vitest"; +import worker from "../src/index"; + +// For now, you'll need to do something like this to get a correctly-typed +// `Request` to pass to `worker.fetch()`. +const IncomingRequest = Request; + +describe("Hello World worker", () => { + it("responds with Hello World! (unit style)", async () => { + const request = new IncomingRequest("http://example.com"); + // Create an empty context to pass to `worker.fetch()`. + const ctx = createExecutionContext(); + const response = await worker.fetch(request, env, ctx); + // Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions + await waitOnExecutionContext(ctx); + expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`); + }); + + it("responds with Hello World! (integration style)", async () => { + const response = await SELF.fetch("https://example.com"); + expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`); + }); +}); diff --git a/edge-api/test/tsconfig.json b/edge-api/test/tsconfig.json new file mode 100644 index 0000000000..978ecd87b7 --- /dev/null +++ b/edge-api/test/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["@cloudflare/vitest-pool-workers"] + }, + "include": ["./**/*.ts", "../worker-configuration.d.ts"], + "exclude": [] +} diff --git a/edge-api/tsconfig.json b/edge-api/tsconfig.json new file mode 100644 index 0000000000..8c98cdbece --- /dev/null +++ b/edge-api/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2024", + /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + "lib": ["es2024"], + /* Specify what JSX code is generated. */ + "jsx": "react-jsx", + + /* Specify what module code is generated. */ + "module": "es2022", + /* Specify how TypeScript looks up a file from a given module specifier. */ + "moduleResolution": "Bundler", + /* Enable importing .json files */ + "resolveJsonModule": true, + + /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "allowJs": true, + /* Enable error reporting in type-checked JavaScript files. */ + "checkJs": false, + + /* Disable emitting files from a compilation. */ + "noEmit": true, + + /* Ensure that each file can be safely transpiled without relying on other imports. */ + "isolatedModules": true, + /* Allow 'import x from y' when a module doesn't have a default export. */ + "allowSyntheticDefaultImports": true, + /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true, + + /* Enable all strict type-checking options. */ + "strict": true, + + /* Skip type checking all .d.ts files. */ + "skipLibCheck": true, + "types": [ + "./worker-configuration.d.ts", + "node" + ] + }, + "exclude": ["test"], + "include": ["worker-configuration.d.ts", "src/**/*.ts"] +} diff --git a/edge-api/vitest.config.mts b/edge-api/vitest.config.mts new file mode 100644 index 0000000000..7ccad75efa --- /dev/null +++ b/edge-api/vitest.config.mts @@ -0,0 +1,11 @@ +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: "./wrangler.jsonc" }, + }, + }, + }, +}); diff --git a/edge-api/worker-configuration.d.ts b/edge-api/worker-configuration.d.ts new file mode 100644 index 0000000000..6ff5a8b25b --- /dev/null +++ b/edge-api/worker-configuration.d.ts @@ -0,0 +1,13550 @@ +/* eslint-disable */ +// Generated by Wrangler by running `wrangler types` (hash: b739a9c19cff1463949c4db47674ed86) +// Runtime types generated with workerd@1.20260507.1 2026-05-09 nodejs_compat +declare namespace Cloudflare { + interface GlobalProps { + mainModule: typeof import("./src/index"); + } + interface Env { + } +} +interface Env extends Cloudflare.Env {} + +// Begin runtime types +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare var onmessage: never; +/** + * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) + */ +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ + readonly message: string; + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ + readonly name: string; + /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); +} +type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * + * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) + */ +interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** + * The **`console.clear()`** static method clears the console if possible. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) + */ + clear(): void; + /** + * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) + */ + count(label?: string): void; + /** + * The **`console.countReset()`** static method resets counter used with console/count_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) + */ + countReset(label?: string): void; + /** + * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) + */ + debug(...data: any[]): void; + /** + * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) + */ + dir(item?: any, options?: any): void; + /** + * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) + */ + dirxml(...data: any[]): void; + /** + * The **`console.error()`** static method outputs a message to the console at the 'error' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) + */ + error(...data: any[]): void; + /** + * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) + */ + group(...data: any[]): void; + /** + * The **`console.groupCollapsed()`** static method creates a new inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) + */ + groupCollapsed(...data: any[]): void; + /** + * The **`console.groupEnd()`** static method exits the current inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) + */ + groupEnd(): void; + /** + * The **`console.info()`** static method outputs a message to the console at the 'info' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) + */ + info(...data: any[]): void; + /** + * The **`console.log()`** static method outputs a message to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) + */ + log(...data: any[]): void; + /** + * The **`console.table()`** static method displays tabular data as a table. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) + */ + table(tabularData?: any, properties?: string[]): void; + /** + * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) + */ + time(label?: string): void; + /** + * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) + */ + timeEnd(label?: string): void; + /** + * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) + */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** + * The **`console.trace()`** static method outputs a stack trace to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) + */ + trace(...data: any[]): void; + /** + * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) + */ + warn(...data: any[]): void; +} +declare const console: Console; +type BufferSource = ArrayBufferView | ArrayBuffer; +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; +declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; +/** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ +declare function btoa(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ +declare function atob(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ +declare function reportError(error: any): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ +declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare const self: ServiceWorkerGlobalScope; +/** +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare const crypto: Crypto; +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +/** +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare const performance: Performance; +declare const Cloudflare: Cloudflare; +declare const origin: string; +declare const navigator: Navigator; +interface TestController { +} +interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; + cache?: CacheContext; + tracing?: Tracing; +} +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + connect?: ExportedHandlerConnectHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class Navigator { + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly platform: string; + readonly language: string; + readonly languages: string[]; +} +interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; + readonly scheduledTime: number; +} +interface Cloudflare { + readonly compatibilityFlags: Record; +} +interface CachePurgeError { + code: number; + message: string; +} +interface CachePurgeResult { + success: boolean; + errors: CachePurgeError[]; +} +interface CachePurgeOptions { + tags?: string[]; + pathPrefixes?: string[]; + purgeEverything?: boolean; +} +interface CacheContext { + purge(options: CachePurgeOptions): Promise; +} +declare abstract class ColoLocalActorNamespace { + get(actorId: string): Fetcher; +} +interface DurableObject { + fetch(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher & { + readonly id: DurableObjectId; + readonly name?: string; +}; +interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; + readonly jurisdiction?: string; +} +declare abstract class DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; +interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; +interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; +} +interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { +} +interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + facets: DurableObjectFacets; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; +} +interface DurableObjectTransaction { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +interface DurableObjectStorage { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; +} +interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +interface DurableObjectFacets { + get(name: string, getStartupOptions: () => FacetStartupOptions | Promise>): Fetcher; + abort(name: string, reason: any): void; + delete(name: string): void; +} +interface FacetStartupOptions { + id?: DurableObjectId | string; + class: DurableObjectClass; +} +interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +/** + * The **`Event`** interface represents an event which takes place on an `EventTarget`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) + */ +declare class Event { + constructor(type: string, init?: EventInit); + /** + * The **`type`** read-only property of the Event interface returns a string containing the event's type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * The read-only **`target`** property of the dispatched. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +type EventListener = (event: EventType) => void; +interface EventListenerObject { + handleEvent(event: EventType): void; +} +type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +/** + * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) + */ +declare class EventTarget = Record> { + constructor(); + /** + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +interface EventTargetEventListenerOptions { + capture?: boolean; +} +interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +/** + * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) + */ +declare class AbortController { + constructor(); + /** + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +/** + * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) + */ +declare abstract class AbortSignal extends EventTarget { + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ + static abort(reason?: any): AbortSignal; + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ + static timeout(delay: number): AbortSignal; + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ + get reason(): any; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ + throwIfAborted(): void; +} +interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +interface SchedulerWaitOptions { + signal?: AbortSignal; +} +/** + * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) + */ +declare abstract class ExtendableEvent extends Event { + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ + waitUntil(promise: Promise): void; +} +/** + * The **`CustomEvent`** interface represents events initialized by an application for any purpose. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) + */ +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +/** + * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) + */ +declare class Blob { + constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ + get size(): number; + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ + get type(): string; + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ + arrayBuffer(): Promise; + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ + bytes(): Promise; + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ + text(): Promise; + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ + stream(): ReadableStream; +} +interface BlobOptions { + type?: string; +} +/** + * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) + */ +declare class File extends Blob { + constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ + get name(): string; + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ + get lastModified(): number; +} +interface FileOptions { + type?: string; + lastModified?: number; +} +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare abstract class CacheStorage { + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ + open(cacheName: string): Promise; + readonly default: Cache; +} +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare abstract class Cache { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; +} +interface CacheQueryOptions { + ignoreMethod?: boolean; +} +/** +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare abstract class Crypto { + /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ + getRandomValues(buffer: T): T; + /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +/** + * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) + */ +declare abstract class SubtleCrypto { + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ + encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ + decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ + sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ + verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ + generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ + deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ + deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ + importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ + exportKey(format: string, key: CryptoKey): Promise; + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ + unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; +} +/** + * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +declare abstract class CryptoKey { + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ + readonly type: string; + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ + readonly extractable: boolean; + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ + readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ + readonly usages: string[]; +} +interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: (ArrayBuffer | ArrayBufferView); + iterations?: number; + hash?: (string | SubtleCryptoHashAlgorithm); + $public?: CryptoKey; + info?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: (ArrayBuffer | ArrayBufferView); + additionalData?: (ArrayBuffer | ArrayBufferView); + tagLength?: number; + counter?: (ArrayBuffer | ArrayBufferView); + length?: number; + label?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + modulusLength?: number; + publicExponent?: (ArrayBuffer | ArrayBufferView); + length?: number; + namedCurve?: string; +} +interface SubtleCryptoHashAlgorithm { + name: string; +} +interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + length?: number; + namedCurve?: string; + compressed?: boolean; +} +interface SubtleCryptoSignAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + dataLength?: number; + saltLength?: number; +} +interface CryptoKeyKeyAlgorithm { + name: string; +} +interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; +} +interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; +} +/** + * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) + */ +declare class TextDecoder { + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +/** + * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) + */ +declare class TextEncoder { + constructor(); + /** + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; +} +interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +interface TextDecoderDecodeOptions { + stream: boolean; +} +interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +/** + * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) + */ +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ + get filename(): string; + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ + get message(): string; + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ + get lineno(): number; + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ + get colno(): number; + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ + get error(): any; +} +interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +/** + * The **`MessageEvent`** interface represents a message received by a target object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) + */ +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + /** + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * The **`origin`** read-only property of the origin of the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * The **`lastEventId`** read-only property of the unique ID for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; +} +interface MessageEventInit { + data: ArrayBuffer | string; +} +/** + * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) + */ +declare abstract class PromiseRejectionEvent extends Event { + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; +} +/** + * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) + */ +declare class FormData { + constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: Blob, filename?: string): void; + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ + delete(name: string): void; + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ + get(name: string): (File | string) | null; + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[]; + /** + * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: Blob, filename?: string): void; + /* Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[ + key: string, + value: File | string + ]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator<(File | string)>; + forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: File | string + ]>; +} +interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +interface EndTag { + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; +} +interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; +} +interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +/** + * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) + */ +declare abstract class FetchEvent extends ExtendableEvent { + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +type HeadersInit = Headers | Iterable> | Record; +/** + * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) + */ +declare class Headers { + constructor(init?: HeadersInit); + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ + get(name: string): string | null; + getAll(name: string): string[]; + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ + getSetCookie(): string[]; + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ + set(name: string, value: string): void; + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ + delete(name: string): void; + forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable | AsyncIterable; +declare abstract class Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; +} +/** + * The **`Response`** interface of the Fetch API represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +declare var Response: { + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: (ResponseInit | Response)): Response; +}; +/** + * The **`Response`** interface of the Fetch API represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +interface Response extends Body { + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ + clone(): Response; + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ + status: number; + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ + statusText: string; + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ + ok: boolean; + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ + redirected: boolean; + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ + type: "default" | "error"; +} +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: (WebSocket | null); + encodeBody?: "automatic" | "manual"; +} +type RequestInfo> = Request | string; +/** + * The **`Request`** interface of the Fetch API represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +declare var Request: { + prototype: Request; + new >(input: RequestInfo | URL, init?: RequestInit): Request; +}; +/** + * The **`Request`** interface of the Fetch API represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +interface Request> extends Body { + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ + clone(): Request; + /** + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * The **`url`** read-only property of the Request interface contains the URL of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf?: Cf; + /** + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; + /** + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: "no-store" | "no-cache"; +} +interface RequestInit { + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: (Fetcher | null); + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: "no-store" | "no-cache"; + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /* An AbortSignal to set request's signal. */ + signal?: (AbortSignal | null); + encodeResponseBody?: "automatic" | "manual"; +} +type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; +type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; +} | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; +}; +interface KVNamespace { + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get(key: Array, type: "json"): Promise>; + get(key: Array, options?: Partial>): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; + list(options?: KVNamespaceListOptions): Promise>; + put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; + getWithMetadata(key: Key, options?: Partial>): Promise>; + getWithMetadata(key: Key, type: "text"): Promise>; + getWithMetadata(key: Key, type: "json"): Promise>; + getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; + getWithMetadata(key: Key, type: "stream"): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; + getWithMetadata(key: Array, type: "text"): Promise>>; + getWithMetadata(key: Array, type: "json"): Promise>>; + getWithMetadata(key: Array, options?: Partial>): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; + delete(key: Key): Promise; +} +interface KVNamespaceListOptions { + limit?: number; + prefix?: (string | null); + cursor?: (string | null); +} +interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: (any | null); +} +interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +type QueueContentType = "text" | "bytes" | "json" | "v8"; +interface Queue { + metrics(): Promise; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; +} +interface QueueSendMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendMetadata { + metrics: QueueSendMetrics; +} +interface QueueSendResponse { + metadata: QueueSendMetadata; +} +interface QueueSendBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendBatchMetadata { + metrics: QueueSendBatchMetrics; +} +interface QueueSendBatchResponse { + metadata: QueueSendBatchMetadata; +} +interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueSendBatchOptions { + delaySeconds?: number; +} +interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetadata { + metrics: MessageBatchMetrics; +} +interface QueueRetryOptions { + delaySeconds?: number; +} +interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + readonly metadata: MessageBatchMetadata; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + readonly metadata: MessageBatchMetadata; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +interface R2Bucket { + head(key: string): Promise; + get(key: string, options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + get(key: string, options?: R2GetOptions): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; +} +interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = { + offset: number; + length?: number; +} | { + offset?: number; + length: number; +} | { + suffix: number; +}; +interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +interface R2GetOptions { + onlyIf?: (R2Conditional | Headers); + range?: (R2Range | Headers); + ssecKey?: (ArrayBuffer | string); +} +interface R2PutOptions { + onlyIf?: (R2Conditional | Headers); + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + md5?: ((ArrayBuffer | ArrayBufferView) | string); + sha1?: ((ArrayBuffer | ArrayBufferView) | string); + sha256?: ((ArrayBuffer | ArrayBufferView) | string); + sha384?: ((ArrayBuffer | ArrayBufferView) | string); + sha512?: ((ArrayBuffer | ArrayBufferView) | string); + storageClass?: string; + ssecKey?: (ArrayBuffer | string); +} +interface R2MultipartOptions { + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + storageClass?: string; + ssecKey?: (ArrayBuffer | string); +} +interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ({ + truncated: true; + cursor: string; +} | { + truncated: false; +}); +interface R2UploadPartOptions { + ssecKey?: (ArrayBuffer | string); +} +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface QueuingStrategy { + highWaterMark?: (number | bigint); + size?: (chunk: T) => number | bigint; +} +interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +interface UnderlyingSource { + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: (number | bigint); +} +interface Transformer { + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = { + done: false; + value: R; +} | { + done: true; + value?: undefined; +}; +/** + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +interface ReadableStream { + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ + get locked(): boolean; + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ + cancel(reason?: any): Promise; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(): ReadableStreamDefaultReader; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; +} +/** + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; +/** + * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) + */ +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ + read(): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ + releaseLock(): void; +} +/** + * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) + */ +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ + read(view: T): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ + releaseLock(): void; + readAtLeast(minElements: number, view: T): Promise>; +} +interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** + * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) + */ +declare abstract class ReadableStreamBYOBRequest { + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ + get view(): Uint8Array | null; + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ + respond(bytesWritten: number): void; + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** + * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) + */ +declare abstract class ReadableStreamDefaultController { + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ + enqueue(chunk?: R): void; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ + error(reason: any): void; +} +/** + * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) + */ +declare abstract class ReadableByteStreamController { + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ + error(reason: any): void; +} +/** + * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare abstract class WritableStreamDefaultController { + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ + get signal(): AbortSignal; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ + error(reason?: any): void; +} +/** + * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) + */ +declare abstract class TransformStreamDefaultController { + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ + enqueue(chunk?: O): void; + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ + error(reason: any): void; + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ + terminate(): void; +} +interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; +} +/** + * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) + */ +declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ + get locked(): boolean; + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) + */ +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ + get closed(): Promise; + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ + get ready(): Promise; + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; +} +/** + * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) + */ +declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ + get readable(): ReadableStream; + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare class IdentityTransformStream extends TransformStream { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: (number | bigint); +} +interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +/** + * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) + */ +declare class CompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/** + * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) + */ +declare class DecompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/** + * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) + */ +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +/** + * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) + */ +declare class TextDecoderStream extends TransformStream { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +/** + * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) + */ +declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +/** + * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) + */ +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; +} +interface TracePreviewInfo { + id: string; + slug: string; + name: string; +} +interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +interface TraceItem { + readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly tailAttributes?: Record; + readonly preview?: TracePreviewInfo; + readonly durableObjectId?: string; + readonly outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; +} +interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +interface TraceItemConnectEventInfo { +} +interface TraceItemCustomEventInfo { +} +interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; +} +interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +/** + * The **`URL`** interface is used to parse, construct, normalize, and encode URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) + */ +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ + get origin(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + get href(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + set href(value: string); + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + get protocol(): string; + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + set protocol(value: string); + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + get username(): string; + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + set username(value: string); + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + get password(): string; + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + set password(value: string); + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + get host(): string; + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + set host(value: string); + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + get hostname(): string; + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + set hostname(value: string); + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + get port(): string; + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + set port(value: string); + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + get pathname(): string; + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + set pathname(value: string); + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + get search(): string; + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + set search(value: string); + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + get hash(): string; + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + set hash(value: string); + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ + get searchParams(): URLSearchParams; + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ + static canParse(url: string, base?: string): boolean; + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ + static parse(url: string, base?: string): URL | null; + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ + static createObjectURL(object: File | Blob): string; + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ + static revokeObjectURL(object_url: string): void; +} +/** + * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) + */ +declare class URLSearchParams { + constructor(init?: (Iterable> | Record | string)); + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ + get size(): number; + /** + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ + sort(): void; + /* Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +declare class URLPattern { + constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + get hasRegExpGroups(): boolean; + test(input?: (string | URLPatternInit), baseURL?: string): boolean; + exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; +} +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +interface URLPatternComponentResult { + input: string; + groups: Record; +} +interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; +} +interface URLPatternOptions { + ignoreCase?: boolean; +} +/** + * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +/** + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +declare var WebSocket: { + prototype: WebSocket; + new (url: string, protocols?: (string[] | string)): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; +}; +/** + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +interface WebSocket extends EventTarget { + accept(options?: WebSocketAcceptOptions): void; + /** + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +interface SqlStorage { + exec>(query: string, ...bindings: any[]): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement { +} +type SqlStorageValue = ArrayBuffer | string | number | null; +declare abstract class SqlStorageCursor> { + next(): { + done?: false; + value: T; + } | { + done: true; + value?: never; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; +} +interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: (number | bigint); +} +interface SocketAddress { + hostname: string; + port: number; +} +interface TlsOptions { + expectedServerHostname?: string; +} +interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ +declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} +interface Container { + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + destroy(error?: any): Promise; + signal(signo: number): void; + getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; + snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise; + snapshotContainer(options: ContainerSnapshotOptions): Promise; + interceptOutboundHttps(addr: string, binding: Fetcher): Promise; +} +interface ContainerDirectorySnapshot { + id: string; + size: number; + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotOptions { + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotRestoreParams { + snapshot: ContainerDirectorySnapshot; + mountPoint?: string; +} +interface ContainerSnapshot { + id: string; + size: number; + name?: string; +} +interface ContainerSnapshotOptions { + name?: string; +} +interface ContainerStartupOptions { + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + labels?: Record; + directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; + containerSnapshot?: ContainerSnapshot; +} +/** + * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) + */ +declare abstract class MessagePort extends EventTarget { + /** + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); +} +/** + * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) + */ +declare class MessageChannel { + constructor(); + /** + * The **`port1`** read-only property of the the port attached to the context that originated the channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort; + /** + * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort; +} +interface MessagePortPostMessageOptions { + transfer?: any[]; +} +type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; +type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { + props?: Props; +}) => Fetcher : (opts: { + props?: any; +}) => Fetcher); +type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { + props?: Props; +}) => DurableObjectClass : (opts: { + props?: any; +}) => DurableObjectClass); +interface LoopbackDurableObjectNamespace extends DurableObjectNamespace { +} +interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace { +} +interface SyncKvStorage { + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[ + string, + T + ]>; + put(key: string, value: T): void; + delete(key: string): boolean; +} +interface SyncKvListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; +} +interface WorkerStub { + getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; + getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; +} +interface WorkerStubEntrypointOptions { + props?: any; + limits?: workerdResourceLimits; +} +interface WorkerLoader { + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; +} +interface WorkerLoaderModule { + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; + wasm?: ArrayBuffer; +} +interface WorkerLoaderWorkerCode { + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + limits?: workerdResourceLimits; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: (Fetcher | null); + tails?: Fetcher[]; + streamingTails?: Fetcher[]; +} +interface workerdResourceLimits { + cpuMs?: number; + subRequests?: number; +} +/** +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare abstract class Performance { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +interface Tracing { + enterSpan(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T; + Span: typeof Span; +} +declare abstract class Span { + get isTraced(): boolean; + setAttribute(key: string, value?: (boolean | number | string)): void; +} +// ============ AI Search Error Interfaces ============ +interface AiSearchInternalError extends Error { +} +interface AiSearchNotFoundError extends Error { +} +// ============ AI Search Common Types ============ +/** A single message in a conversation-style search or chat request. */ +type AiSearchMessage = { + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; +}; +/** + * Common shape for `ai_search_options` used by both single-instance and multi-instance requests. + * Contains retrieval, query rewrite, reranking, and cache sub-options. + */ +type AiSearchOptions = { + retrieval?: { + /** Which retrieval backend to use. Defaults to the instance's configured index_method. */ + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Fusion method for combining vector + keyword results. */ + fusion_method?: 'max' | 'rrf'; + /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */ + keyword_match_mode?: 'and' | 'or'; + /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */ + match_threshold?: number; + /** Maximum number of results to return (1-50). Default 10. */ + max_num_results?: number; + /** Vectorize metadata filters applied to the search. */ + filters?: VectorizeVectorMetadataFilter; + /** Number of surrounding chunks to include for context (0-3). Default 0. */ + context_expansion?: number; + /** If true, return only item metadata without chunk text. */ + metadata_only?: boolean; + /** If true (default), return empty results on retrieval failure instead of throwing. */ + return_on_failure?: boolean; + /** Boost results by metadata field values. Max 3 entries. */ + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: string; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + cache?: { + enabled?: boolean; + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + }; + [key: string]: unknown; +}; +// ============ AI Search Request Types ============ +/** + * Request body for single-instance search. + * Exactly one of `query` or `messages` must be provided. + */ +type AiSearchSearchRequest = { + /** Simple query string. */ + query: string; + messages?: never; + ai_search_options?: AiSearchOptions; +} | { + query?: never; + /** Conversation-style input. At least one user message with non-empty content is required. */ + messages: AiSearchMessage[]; + ai_search_options?: AiSearchOptions; +}; +type AiSearchChatCompletionsRequest = { + messages: AiSearchMessage[]; + model?: string; + stream?: boolean; + ai_search_options?: AiSearchOptions; + [key: string]: unknown; +}; +// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============ +/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */ +type AiSearchMultiSearchOptions = AiSearchOptions & { + /** Instance IDs to search across (1-10). */ + instance_ids: string[]; +}; +/** + * Request for searching across multiple instances within a namespace. + * `ai_search_options` is required and must include `instance_ids`. + * Exactly one of `query` or `messages` must be provided. + */ +type AiSearchMultiSearchRequest = { + /** Simple query string. */ + query: string; + messages?: never; + ai_search_options: AiSearchMultiSearchOptions; +} | { + query?: never; + /** Conversation-style input. */ + messages: AiSearchMessage[]; + ai_search_options: AiSearchMultiSearchOptions; +}; +/** A search result chunk tagged with the instance it originated from. */ +type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & { + instance_id: string; +}; +/** Describes a per-instance error during a multi-instance operation. */ +type AiSearchMultiSearchError = { + instance_id: string; + message: string; +}; +/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiSearchResponse = { + search_query: string; + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; +}; +/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */ +type AiSearchMultiChatCompletionsRequest = Omit & { + ai_search_options: AiSearchMultiSearchOptions; +}; +/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiChatCompletionsResponse = Omit & { + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; +}; +// ============ AI Search Response Types ============ +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + /** Keyword rank position */ + keyword_rank?: number; + /** Vector rank position */ + vector_rank?: number; + /** Reranking model score */ + reranking_score?: number; + /** Fusion method used to combine results */ + fusion_method?: 'rrf' | 'max'; + [key: string]: unknown; + }; + }>; +}; +type AiSearchChatCompletionsResponse = { + id?: string; + object?: string; + model?: string; + choices: Array<{ + index?: number; + message: { + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + [key: string]: unknown; + }; + [key: string]: unknown; + }>; + chunks: AiSearchSearchResponse['chunks']; + [key: string]: unknown; +}; +type AiSearchStatsResponse = { + queued?: number; + running?: number; + completed?: number; + error?: number; + skipped?: number; + outdated?: number; + last_activity?: string; + /** Storage engine statistics. */ + engine?: { + vectorize?: { + vectorsCount: number; + dimensions: number; + }; + r2?: { + payloadSizeBytes: number; + metadataSizeBytes: number; + objectCount: number; + }; + }; +}; +// ============ AI Search Instance Info Types ============ +type AiSearchInstanceInfo = { + id: string; + type?: 'r2' | 'web-crawler' | string; + source?: string; + source_params?: unknown; + paused?: boolean; + status?: string; + namespace?: string; + created_at?: string; + modified_at?: string; + token_id?: string; + ai_gateway_id?: string; + rewrite_query?: boolean; + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are active. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. */ + fusion_method?: 'max' | 'rrf'; + indexing_options?: { + keyword_tokenizer?: 'porter' | 'trigram'; + } | null; + retrieval_options?: { + keyword_match_mode?: 'and' | 'or'; + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + custom_metadata?: Array<{ + field_name: string; + data_type: 'text' | 'number' | 'boolean' | 'datetime'; + }>; + /** Sync interval in seconds. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; +}; +/** Pagination, search, and ordering parameters for listing instances within a namespace. */ +type AiSearchListInstancesParams = { + page?: number; + per_page?: number; + /** Search instances by ID. */ + search?: string; + /** Field to sort by. */ + order_by?: 'created_at'; + /** Sort direction. */ + order_by_direction?: 'asc' | 'desc'; +}; +type AiSearchListResponse = { + result: AiSearchInstanceInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Config Types ============ +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + /** Instance type. Omit to create with built-in storage. */ + type?: 'r2' | 'web-crawler' | string; + /** Source URL (required for web-crawler type). */ + source?: string; + source_params?: unknown; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are used during indexing. Defaults to vector-only. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */ + fusion_method?: 'max' | 'rrf'; + indexing_options?: { + keyword_tokenizer?: 'porter' | 'trigram'; + } | null; + retrieval_options?: { + keyword_match_mode?: 'and' | 'or'; + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + /** Minimum similarity score (0-1) for a result to be included. */ + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */ + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + custom_metadata?: Array<{ + field_name: string; + data_type: 'text' | 'number' | 'boolean' | 'datetime'; + }>; + namespace?: string; + /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; +}; +// ============ AI Search Item Types ============ +type AiSearchItemInfo = { + id: string; + key: string; + status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated'; + next_action?: 'INDEX' | 'DELETE' | null; + error?: string; + checksum?: string; + namespace?: string; + chunks_count?: number | null; + file_size?: number | null; + source_id?: string | null; + last_seen_at?: string; + created_at?: string; + metadata?: Record; + [key: string]: unknown; +}; +type AiSearchItemContentResult = { + body: ReadableStream; + contentType: string; + filename: string; + size: number; +}; +type AiSearchUploadItemOptions = { + metadata?: Record; +}; +type AiSearchListItemsParams = { + page?: number; + per_page?: number; + /** Search items by key name. */ + search?: string; + /** Sort order for results. */ + sort_by?: 'status' | 'modified_at'; + /** Filter items by processing status. */ + status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated'; + /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */ + source?: string; + /** JSON-encoded Vectorize filter for metadata filtering. */ + metadata_filter?: string; +}; +type AiSearchListItemsResponse = { + result: AiSearchItemInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Item Logs Types ============ +type AiSearchItemLogsParams = { + /** Maximum number of log entries to return (1-100, default 50). */ + limit?: number; + /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */ + cursor?: string; +}; +type AiSearchItemLog = { + timestamp: string; + action: string; + message: string; + fileKey?: string; + chunkCount?: number; + processingTimeMs?: number; + errorType?: string; +}; +/** Paginated response for item processing logs (cursor-based). */ +type AiSearchItemLogsResponse = { + result: AiSearchItemLog[]; + result_info: { + count: number; + per_page: number; + cursor: string | null; + truncated: boolean; + }; +}; +// ============ AI Search Item Chunks Types ============ +type AiSearchItemChunksParams = { + /** Maximum number of chunks to return (1-100, default 20). */ + limit?: number; + /** Offset into the chunks list (default 0). */ + offset?: number; +}; +/** A single indexed chunk belonging to an item, including its text content and byte range. */ +type AiSearchItemChunk = { + id: string; + text: string; + start_byte: number; + end_byte: number; + item?: { + timestamp?: number; + key: string; + metadata?: Record; + }; +}; +/** Paginated response for item chunks (offset-based). */ +type AiSearchItemChunksResponse = { + result: AiSearchItemChunk[]; + result_info: { + count: number; + total: number; + limit: number; + offset: number; + }; +}; +// ============ AI Search Job Types ============ +type AiSearchJobInfo = { + id: string; + source: 'user' | 'schedule'; + description?: string; + last_seen_at?: string; + started_at?: string; + ended_at?: string; + end_reason?: string; +}; +type AiSearchJobLog = { + id: number; + message: string; + message_type: number; + created_at: number; +}; +type AiSearchCreateJobParams = { + description?: string; +}; +type AiSearchListJobsParams = { + page?: number; + per_page?: number; +}; +type AiSearchListJobsResponse = { + result: AiSearchJobInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +type AiSearchJobLogsParams = { + page?: number; + per_page?: number; +}; +type AiSearchJobLogsResponse = { + result: AiSearchJobLog[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Sub-Service Classes ============ +/** + * Single item service for an AI Search instance. + * Provides info, download, sync, logs, and chunks operations on a specific item. + */ +declare abstract class AiSearchItem { + /** Get metadata about this item. */ + info(): Promise; + /** + * Download the item's content. + * @returns Object with body stream, content type, filename, and size. + */ + download(): Promise; + /** + * Trigger re-indexing of this item. + * @returns The updated item info. + */ + sync(): Promise; + /** + * Retrieve processing logs for this item (cursor-based pagination). + * @param params Optional pagination parameters (limit, cursor). + * @returns Paginated log entries for this item. + */ + logs(params?: AiSearchItemLogsParams): Promise; + /** + * List indexed chunks for this item (offset-based pagination). + * @param params Optional pagination parameters (limit, offset). + * @returns Paginated chunk entries for this item. + */ + chunks(params?: AiSearchItemChunksParams): Promise; +} +/** + * Items collection service for an AI Search instance. + * Provides list, upload, and access to individual items. + */ +declare abstract class AiSearchItems { + /** List items in this instance. */ + list(params?: AiSearchListItemsParams): Promise; + /** + * Upload a file as an item. Behaves as an upsert: if an item with the same + * filename already exists, it is overwritten and re-indexed. + * @param name Filename for the uploaded item. + * @param content File content as a ReadableStream, Blob, or string. + * @param options Optional metadata to attach to the item. + * @returns The created item info. + */ + upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise; + /** + * Upload a file and poll until processing completes. + * Behaves as an upsert: if an item with the same filename already exists, + * it is overwritten and re-indexed. + * @param name Filename for the uploaded item. + * @param content File content as a ReadableStream, Blob, or string. + * @param options Optional metadata and polling configuration. + * @returns The item info after processing completes (or timeout). + */ + uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & { + /** Polling interval in milliseconds (default 1000). */ + pollIntervalMs?: number; + /** Maximum time to wait in milliseconds (default 30000). */ + timeoutMs?: number; + }): Promise; + /** + * Get an item by ID. + * @param itemId The item identifier. + * @returns Item service for info, download, sync, logs, and chunks operations. + */ + get(itemId: string): AiSearchItem; + /** + * Delete an item from the instance. + * @param itemId The item identifier. + */ + delete(itemId: string): Promise; +} +/** + * Single job service for an AI Search instance. + * Provides info, logs, and cancel operations for a specific job. + */ +declare abstract class AiSearchJob { + /** Get metadata about this job. */ + info(): Promise; + /** Get logs for this job. */ + logs(params?: AiSearchJobLogsParams): Promise; + /** + * Cancel a running job. + * @returns The updated job info. + * @throws AiSearchNotFoundError if the job does not exist. + */ + cancel(): Promise; +} +/** + * Jobs collection service for an AI Search instance. + * Provides list, create, and access to individual jobs. + */ +declare abstract class AiSearchJobs { + /** List jobs for this instance. */ + list(params?: AiSearchListJobsParams): Promise; + /** + * Create a new indexing job. + * @param params Optional job parameters. + * @returns The created job info. + */ + create(params?: AiSearchCreateJobParams): Promise; + /** + * Get a job by ID. + * @param jobId The job identifier. + * @returns Job service for info, logs, and cancel operations. + */ + get(jobId: string): AiSearchJob; +} +// ============ AI Search Binding Classes ============ +/** + * Instance-level AI Search service. + * + * Used as: + * - The return type of `AiSearchNamespace.get(name)` (namespace binding) + * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`) + * + * Provides search, chat, update, stats, items, and jobs operations. + * + * @example + * ```ts + * // Via namespace binding + * const instance = env.AI_SEARCH.get("blog"); + * const results = await instance.search({ + * query: "How does caching work?", + * }); + * + * // Via single instance binding + * const results = await env.BLOG_SEARCH.search({ + * messages: [{ role: "user", content: "How does caching work?" }], + * }); + * ``` + */ +declare abstract class AiSearchInstance { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with query or messages and optional AI search options. + * @returns Search response with matching chunks and search query. + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context (streaming). + * @param params Chat completions request with stream: true. + * @returns ReadableStream of server-sent events. + */ + chatCompletions(params: AiSearchChatCompletionsRequest & { + stream: true; + }): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request. + * @returns Chat completion response with choices and RAG chunks. + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Update the instance configuration. + * @param config Partial configuration to update. + * @returns Updated instance info. + */ + update(config: Partial): Promise; + /** Get metadata about this instance. */ + info(): Promise; + /** + * Get instance statistics (item count, indexing status, etc.). + * @returns Statistics with counts per status, last activity time, and engine details. + */ + stats(): Promise; + /** Items collection — list, upload, and manage items in this instance. */ + get items(): AiSearchItems; + /** Jobs collection — list, create, and inspect indexing jobs. */ + get jobs(): AiSearchJobs; +} +/** + * Namespace-level AI Search service. + * + * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`). + * Scoped to a single namespace. Provides dynamic instance access, creation, deletion, + * and multi-instance search/chat operations. + * + * @example + * ```ts + * // Access an instance within the namespace + * const blog = env.AI_SEARCH.get("blog"); + * const results = await blog.search({ query: "How does caching work?" }); + * + * // List all instances in the namespace + * const instances = await env.AI_SEARCH.list(); + * + * // Create a new instance with built-in storage + * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" }); + * + * // Upload items into the instance + * await tenant.items.upload("doc.pdf", fileContent); + * + * // Search across multiple instances + * const multi = await env.AI_SEARCH.search({ + * query: "caching", + * ai_search_options: { instance_ids: ["blog", "docs"] }, + * }); + * + * // Delete an instance + * await env.AI_SEARCH.delete("tenant-123"); + * ``` + */ +declare abstract class AiSearchNamespace { + /** + * Get an instance by name within the bound namespace. + * @param name Instance name. + * @returns Instance service for search, chat, update, stats, items, and jobs. + */ + get(name: string): AiSearchInstance; + /** + * List instances in the bound namespace. + * @param params Optional pagination, search, and ordering parameters. + * @returns Array of instance metadata with pagination info. + */ + list(params?: AiSearchListInstancesParams): Promise; + /** + * Create a new instance within the bound namespace. + * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage. + * @returns Instance service for the newly created instance. + * + * @example + * ```ts + * // Create with built-in storage (upload items manually) + * const instance = await env.AI_SEARCH.create({ id: "my-search" }); + * + * // Create with web crawler source + * const instance = await env.AI_SEARCH.create({ + * id: "docs-search", + * type: "web-crawler", + * source: "https://developers.cloudflare.com", + * }); + * ``` + */ + create(config: AiSearchConfig): Promise; + /** + * Delete an instance from the bound namespace. + * @param name Instance name to delete. + */ + delete(name: string): Promise; + /** + * Search across multiple instances within the bound namespace. + * Fans out to the specified instance_ids and merges results. + * @param params Search request with required `ai_search_options.instance_ids`. + * @returns Search response with chunks tagged by instance_id and optional partial-failure errors. + */ + search(params: AiSearchMultiSearchRequest): Promise; + /** + * Generate chat completions across multiple instances within the bound namespace (streaming). + * Fans out to the specified instance_ids, merges context, and generates a response. + * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`. + * @returns ReadableStream of server-sent events. + */ + chatCompletions(params: AiSearchMultiChatCompletionsRequest & { + stream: true; + }): Promise; + /** + * Generate chat completions across multiple instances within the bound namespace. + * Fans out to the specified instance_ids, merges context, and generates a response. + * @param params Chat completions request with required `ai_search_options.instance_ids`. + * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors. + */ + chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise; +} +type AiImageClassificationInput = { + image: number[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +type AiImageTextToTextInput = { + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; +}; +type AiIMultimodalEmbeddingsOutput = { + data: number[][]; + shape: number[]; +}; +declare abstract class BaseAiMultimodalEmbeddings { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiObjectDetectionInput = { + image: number[]; +}; +type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +type AiAutomaticSpeechRecognitionInput = { + audio: number[]; +}; +type AiAutomaticSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiAutomaticSpeechRecognition { + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; +} +type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +type AiTextClassificationInput = { + text: string; +}; +type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +type AiTextEmbeddingsInput = { + text: string | string[]; +}; +type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +type RoleScopedChatInput = { + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; +}; +type AiTextGenerationToolLegacyInput = { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; +type AiTextGenerationFunctionsInput = { + name: string; + code: string; +}; +type AiTextGenerationResponseFormat = { + type: string; + json_schema?: any; +}; +type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; +}; +type AiTextGenerationToolLegacyOutput = { + name: string; + arguments: unknown; +}; +type AiTextGenerationToolOutput = { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +}; +type UsageTags = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; +type AiTextGenerationOutput = { + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; +}; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +type AiTextToSpeechInput = { + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = Uint8Array | { + audio: string; +}; +declare abstract class BaseAiTextToSpeech { + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; +} +type AiTextToImageInput = { + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +/** + * Workers AI support for OpenAI's Chat Completions API + */ +type ChatCompletionContentPartText = { + type: "text"; + text: string; +}; +type ChatCompletionContentPartImage = { + type: "image_url"; + image_url: { + url: string; + detail?: "auto" | "low" | "high"; + }; +}; +type ChatCompletionContentPartInputAudio = { + type: "input_audio"; + input_audio: { + /** Base64 encoded audio data. */ + data: string; + format: "wav" | "mp3"; + }; +}; +type ChatCompletionContentPartFile = { + type: "file"; + file: { + /** Base64 encoded file data. */ + file_data?: string; + /** The ID of an uploaded file. */ + file_id?: string; + filename?: string; + }; +}; +type ChatCompletionContentPartRefusal = { + type: "refusal"; + refusal: string; +}; +type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile; +type FunctionDefinition = { + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; +}; +type ChatCompletionFunctionTool = { + type: "function"; + function: FunctionDefinition; +}; +type ChatCompletionCustomToolGrammarFormat = { + type: "grammar"; + grammar: { + definition: string; + syntax: "lark" | "regex"; + }; +}; +type ChatCompletionCustomToolTextFormat = { + type: "text"; +}; +type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat; +type ChatCompletionCustomTool = { + type: "custom"; + custom: { + name: string; + description?: string; + format?: ChatCompletionCustomToolFormat; + }; +}; +type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; +type ChatCompletionMessageFunctionToolCall = { + id: string; + type: "function"; + function: { + name: string; + /** JSON-encoded arguments string. */ + arguments: string; + }; +}; +type ChatCompletionMessageCustomToolCall = { + id: string; + type: "custom"; + custom: { + name: string; + input: string; + }; +}; +type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; +type ChatCompletionToolChoiceFunction = { + type: "function"; + function: { + name: string; + }; +}; +type ChatCompletionToolChoiceCustom = { + type: "custom"; + custom: { + name: string; + }; +}; +type ChatCompletionToolChoiceAllowedTools = { + type: "allowed_tools"; + allowed_tools: { + mode: "auto" | "required"; + tools: Array>; + }; +}; +type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools; +type DeveloperMessage = { + role: "developer"; + content: string | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +type SystemMessage = { + role: "system"; + content: string | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +/** + * Permissive merged content part used inside UserMessage arrays. + * + * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination + * inside nested array items does not correctly match different branches for + * different array elements, so the schema uses a single merged object. + */ +type UserMessageContentPart = { + type: "text" | "image_url" | "input_audio" | "file"; + text?: string; + image_url?: { + url?: string; + detail?: "auto" | "low" | "high"; + }; + input_audio?: { + data?: string; + format?: "wav" | "mp3"; + }; + file?: { + file_data?: string; + file_id?: string; + filename?: string; + }; +}; +type UserMessage = { + role: "user"; + content: string | Array; + name?: string; +}; +type AssistantMessageContentPart = { + type: "text" | "refusal"; + text?: string; + refusal?: string; +}; +type AssistantMessage = { + role: "assistant"; + content?: string | null | Array; + refusal?: string | null; + name?: string; + audio?: { + id: string; + }; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + }; +}; +type ToolMessage = { + role: "tool"; + content: string | Array<{ + type: "text"; + text: string; + }>; + tool_call_id: string; +}; +type FunctionMessage = { + role: "function"; + content: string; + name: string; +}; +type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage; +type ChatCompletionsResponseFormatText = { + type: "text"; +}; +type ChatCompletionsResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatJSONSchema = { + type: "json_schema"; + json_schema: { + name: string; + description?: string; + schema?: Record; + strict?: boolean | null; + }; +}; +type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema; +type ChatCompletionsStreamOptions = { + include_usage?: boolean; + include_obfuscation?: boolean; +}; +type PredictionContent = { + type: "content"; + content: string | Array<{ + type: "text"; + text: string; + }>; +}; +type AudioParams = { + voice: string | { + id: string; + }; + format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; +}; +type WebSearchUserLocation = { + type: "approximate"; + approximate: { + city?: string; + country?: string; + region?: string; + timezone?: string; + }; +}; +type WebSearchOptions = { + search_context_size?: "low" | "medium" | "high"; + user_location?: WebSearchUserLocation; +}; +type ChatTemplateKwargs = { + /** Whether to enable reasoning, enabled by default. */ + enable_thinking?: boolean; + /** If false, preserves reasoning context between turns. */ + clear_thinking?: boolean; +}; +/** Shared optional properties used by both Prompt and Messages input branches. */ +type ChatCompletionsCommonOptions = { + model?: string; + audio?: AudioParams; + frequency_penalty?: number | null; + logit_bias?: Record | null; + logprobs?: boolean | null; + top_logprobs?: number | null; + max_tokens?: number | null; + max_completion_tokens?: number | null; + metadata?: Record | null; + modalities?: Array<"text" | "audio"> | null; + n?: number | null; + parallel_tool_calls?: boolean; + prediction?: PredictionContent; + presence_penalty?: number | null; + reasoning_effort?: "low" | "medium" | "high" | null; + chat_template_kwargs?: ChatTemplateKwargs; + response_format?: ResponseFormat; + seed?: number | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stop?: string | Array | null; + store?: boolean | null; + stream?: boolean | null; + stream_options?: ChatCompletionsStreamOptions; + temperature?: number | null; + tool_choice?: ChatCompletionToolChoiceOption; + tools?: Array; + top_p?: number | null; + user?: string; + web_search_options?: WebSearchOptions; + function_call?: "none" | "auto" | { + name: string; + }; + functions?: Array; +}; +type PromptTokensDetails = { + cached_tokens?: number; + audio_tokens?: number; +}; +type CompletionTokensDetails = { + reasoning_tokens?: number; + audio_tokens?: number; + accepted_prediction_tokens?: number; + rejected_prediction_tokens?: number; +}; +type CompletionUsage = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + prompt_tokens_details?: PromptTokensDetails; + completion_tokens_details?: CompletionTokensDetails; +}; +type ChatCompletionTopLogprob = { + token: string; + logprob: number; + bytes: Array | null; +}; +type ChatCompletionTokenLogprob = { + token: string; + logprob: number; + bytes: Array | null; + top_logprobs: Array; +}; +type ChatCompletionAudio = { + id: string; + /** Base64 encoded audio bytes. */ + data: string; + expires_at: number; + transcript: string; +}; +type ChatCompletionUrlCitation = { + type: "url_citation"; + url_citation: { + url: string; + title: string; + start_index: number; + end_index: number; + }; +}; +type ChatCompletionResponseMessage = { + role: "assistant"; + content: string | null; + refusal: string | null; + annotations?: Array; + audio?: ChatCompletionAudio; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + } | null; +}; +type ChatCompletionLogprobs = { + content: Array | null; + refusal?: Array | null; +}; +type ChatCompletionChoice = { + index: number; + message: ChatCompletionResponseMessage; + finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; + logprobs: ChatCompletionLogprobs | null; +}; +type ChatCompletionsPromptInput = { + prompt: string; +} & ChatCompletionsCommonOptions; +type ChatCompletionsMessagesInput = { + messages: Array; +} & ChatCompletionsCommonOptions; +type ChatCompletionsOutput = { + id: string; + object: string; + created: number; + model: string; + choices: Array; + usage?: CompletionUsage; + system_fingerprint?: string | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; +}; +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; +/** Marks keys from T that aren't in U as optional never */ +type Without = { + [P in Exclude]?: never; +}; +/** Either T or U, but not both (mutually exclusive) */ +type XOR = (T & Without) | (U & Without); +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +} +type Ai_Cf_Openai_Whisper_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + }[]; +}; +type Ai_Cf_Meta_M2M100_1_2B_Output = { + /** + * The translated text in the target language + */ + translated_text?: string; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +} +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +} +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +} +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; +}; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + audio: string | { + body?: object; + contentType?: string; + }; + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string; + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean; + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string; + /** + * The prefix appended to the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; + /** + * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. + */ + beam_size?: number; + /** + * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. + */ + condition_on_previous_text?: boolean; + /** + * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. + */ + no_speech_threshold?: number; + /** + * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. + */ + compression_ratio_threshold?: number; + /** + * Threshold for filtering out segments with low average log probability, indicating low confidence. + */ + log_prob_threshold?: number; + /** + * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. + */ + hallucination_silence_threshold?: number; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + */ + language_probability?: number; + /** + * The total duration of the original audio file, in seconds. + */ + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; +}; +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Output_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Output_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Output_Query { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_Output_Embedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; +} +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + image?: number[] | (string & NonNullable); + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: "user" | "assistant"; + /** + * The content of the message as a string. + */ + content: string; + }[]; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: string | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { + /** + * A query you wish to perform against the provided contexts. + */ + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; +} +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwq_32B_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +} +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} +interface Ai_Cf_Deepgram_Nova_3_Input { + audio: { + body: object; + contentType: string; + }; + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: "extended" | "strict"; + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: "extended" | "strict"; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: "general" | "medical" | "finance"; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean; + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean; + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string; + /** + * Search for terms or phrases in submitted audio. + */ + search?: string; + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean; + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean; + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean; + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean; + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number; + /** + * The number of channels in the submitted audio + */ + channels?: number; + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean; + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; +} +interface Ai_Cf_Deepgram_Nova_3_Output { + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; + }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; + }; + }; + }; +} +declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object; + contentType: string; + }; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +} | { + /** + * base64 encoded audio data + */ + audio: string; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +}; +interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; +} +declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: XOR; + postProcessedOutputs: XOR; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { + inputs: XOR; + postProcessedOutputs: XOR; +} +interface Ai_Cf_Leonardo_Phoenix_1_0_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; +} +/** + * The generated image in JPEG format + */ +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; +} +interface Ai_Cf_Deepgram_Aura_1_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_1_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target langauge to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output; +} +declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +interface AiModels { + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; + "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev; + "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B; + "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B; + "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash; + "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5; + "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; +} +type AiOptions = { + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; + signal?: AbortSignal; +}; +type AiModelsSearchParams = { + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; +type AiModelsSearchObject = { + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +type ChatCompletionsBase = XOR; +type ChatCompletionsInput = XOR; +interface InferenceUpstreamError extends Error { +} +interface AiInternalError extends Error { +} +type AiModelListType = Record; +type AiAsyncBatchResponse = { + request_id: string; +}; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(): AiSearchNamespace; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + * + * @param autoragId Instance ID + */ + autorag(autoragId: string): AutoRAG; + // Batch request + run(model: Name, inputs: { + requests: AiModelList[Name]['inputs'][]; + }, options: AiOptions & { + queueRequest: true; + }): Promise; + // Raw response + run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { + returnRawResponse: true; + }): Promise; + // WebSocket + run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { + websocket: true; + }): Promise; + // Streaming + run(model: Name, inputs: AiModelList[Name]['inputs'] & { + stream: true; + }, options?: AiOptions): Promise; + // Normal (default) - known model + run(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise; + // Unknown model (gateway fallback) + run(model: string & {}, inputs: Record, options?: AiOptions): Promise>; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; +} +type GatewayRetries = { + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; +}; +type GatewayOptions = { + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; +type UniversalGatewayOptions = Exclude & { + /** + ** @deprecated + */ + id?: string; +}; +type AiGatewayPatchLog = { + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; +type AiGatewayLog = { + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; +type AIGatewayHeaders = { + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': { + per_token_in?: number; + per_token_out?: number; + } | { + total_cost?: number; + } | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; +}; +type AIGatewayUniversalRequest = { + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error { +} +interface AiGatewayLogNotFound extends Error { +} +declare abstract class AiGateway { + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + signal?: AbortSignal; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +// Copyright (c) 2022-2025 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Artifacts — Git-compatible file storage on Cloudflare Workers. + * + * Provides programmatic access to create, manage, and fork repositories, + * and to issue and revoke scoped access tokens. + */ +/** Information about a repository. */ +interface ArtifactsRepoInfo { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name (e.g. "main"). */ + defaultBranch: string; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 last-updated timestamp. */ + updatedAt: string; + /** ISO 8601 timestamp of the last push, or null if never pushed. */ + lastPushAt: string | null; + /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */ + source: string | null; + /** Whether the repository is read-only. */ + readOnly: boolean; + /** HTTPS git remote URL. */ + remote: string; +} +/** Result of creating a repository — includes the initial access token. */ +interface ArtifactsCreateRepoResult { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name. */ + defaultBranch: string; + /** HTTPS git remote URL. */ + remote: string; + /** Plaintext access token (only returned at creation time). */ + token: string; + /** ISO 8601 token expiry timestamp. */ + tokenExpiresAt: string; +} +/** Paginated list of repositories. */ +interface ArtifactsRepoListResult { + /** Repositories in this page (without the `remote` field). */ + repos: Omit[]; + /** Total number of repositories in the namespace. */ + total: number; + /** Cursor for the next page, if there are more results. */ + cursor?: string; +} +/** Result of creating an access token. */ +interface ArtifactsCreateTokenResult { + /** Unique token ID. */ + id: string; + /** Plaintext token (only returned at creation time). */ + plaintext: string; + /** Token scope: "read" or "write". */ + scope: 'read' | 'write'; + /** ISO 8601 token expiry timestamp. */ + expiresAt: string; +} +/** Token metadata (no plaintext). */ +interface ArtifactsTokenInfo { + /** Unique token ID. */ + id: string; + /** Token scope: "read" or "write". */ + scope: 'read' | 'write'; + /** Token state: "active", "expired", or "revoked". */ + state: 'active' | 'expired' | 'revoked'; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 expiry timestamp. */ + expiresAt: string; +} +/** Paginated list of tokens for a repository. */ +interface ArtifactsTokenListResult { + /** Tokens in this page. */ + tokens: ArtifactsTokenInfo[]; + /** Total number of tokens for the repository. */ + total: number; +} +/** Handle for a single repository. Returned by Artifacts.get(). */ +interface ArtifactsRepo extends ArtifactsRepoInfo { + /** + * Create an access token for this repo. + * @param scope Token scope: "write" (default) or "read". + * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000). + */ + createToken(scope?: 'write' | 'read', ttl?: number): Promise; + /** List tokens for this repo (metadata only, no plaintext). */ + listTokens(): Promise; + /** + * Revoke a token by plaintext or ID. + * @param tokenOrId Plaintext token or token ID. + * @returns true if revoked, false if not found. + */ + revokeToken(tokenOrId: string): Promise; + // ── Fork ── + /** + * Fork this repo to a new repo. + * @param name Target repository name. + * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). + */ + fork(name: string, opts?: { + description?: string; + readOnly?: boolean; + defaultBranchOnly?: boolean; + }): Promise; +} +/** Artifacts binding — namespace-level operations. */ +interface Artifacts { + /** + * Create a new repository with an initial access token. + * @param name Repository name (alphanumeric, dots, hyphens, underscores). + * @param opts Optional: readOnly flag, description, default branch name. + * @returns Repo metadata with initial token. + */ + create(name: string, opts?: { + readOnly?: boolean; + description?: string; + setDefaultBranch?: string; + }): Promise; + /** + * Get a handle to an existing repository. + * @param name Repository name. + * @returns Repo handle. + */ + get(name: string): Promise; + /** + * Import a repository from an external git remote. + * @param params Source URL and optional branch/depth, plus target name and options. + * @returns Repo metadata with initial token. + */ + import(params: { + source: { + url: string; + branch?: string; + depth?: number; + }; + target: { + name: string; + opts?: { + description?: string; + readOnly?: boolean; + }; + }; + }): Promise; + /** + * List repositories with cursor-based pagination. + * @param opts Optional: limit (1–200, default 50), cursor for next page. + */ + list(opts?: { + limit?: number; + cursor?: string; + }): Promise; + /** + * Delete a repository and all associated tokens. + * @param name Repository name. + * @returns true if deleted, false if not found. + */ + delete(name: string): Promise; +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGInternalError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNotFoundError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGUnauthorizedError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNameNotSetError extends Error { +} +type ComparisonFilter = { + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; +type CompoundFilter = { + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; + system_prompt?: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchResponse = { + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +declare abstract class AutoRAG { + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + list(): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; +} +interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + * - squeeze: Stretches and deforms to the width and height given, even if it + * breaks aspect ratio + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: "foreground"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +interface BasicImageTransformationsGravityCoordinates { + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + /** + * Explicit Cache-Control header value to set on the response stored in cache. + * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400'). + * + * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`), + * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError. + * + * Can be used together with `cacheTtlByStatus`. + */ + cacheControl?: string; + /** + * Whether the response should be eligible for Cache Reserve storage. + */ + cacheReserveEligible?: boolean; + /** + * Whether to respect strong ETags (as opposed to weak ETags) from the origin. + */ + respectStrongEtag?: boolean; + /** + * Whether to strip ETag headers from the origin response before caching. + */ + stripEtags?: boolean; + /** + * Whether to strip Last-Modified headers from the origin response before caching. + */ + stripLastModified?: boolean; + /** + * Whether to enable Cache Deception Armor, which protects against web cache + * deception attacks by verifying the Content-Type matches the URL extension. + */ + cacheDeceptionArmor?: boolean; + /** + * Minimum file size in bytes for a response to be eligible for Cache Reserve storage. + */ + cacheReserveMinimumFileSize?: number; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + r2?: RequestInitCfPropertiesR2; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +interface RequestInitCfPropertiesImage extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * Allows you to trim your image. Takes dpr into account and is performed before + * resizing or rotation. + * + * It can be used as: + * - left, top, right, bottom - it will specify the number of pixels to cut + * off each side + * - width, height - the width/height you'd like to end up with - can be used + * in combination with the properties above + * - border - this will automatically trim the surroundings of an image based on + * it's color. It consists of three properties: + * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) + * - tolerance: difference from color to treat as color + * - keep: the number of pixels of border to keep + */ + trim?: "border" | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number | "low" | "medium-low" | "medium-high" | "high"; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: { + color: string; + width: number; + } | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + saturation?: number; + /** + * Flips the images horizontally, vertically, or both. Flipping is applied before + * rotation, so if you apply flip=h,rotate=90 then the image will be flipped + * horizontally, then rotated by 90 degrees. + */ + flip?: 'h' | 'v' | 'hv'; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +interface RequestInitCfPropertiesR2 { + /** + * Colo id of bucket that an object is stored in + */ + bucketColoId?: number; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +interface IncomingRequestCfPropertiesBase extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn?: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization?: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata?: HostMetadata; +} +interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = +/** Authentication succeeded */ +"SUCCESS" +/** No certificate was presented */ + | "NONE" +/** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" +/** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" +/** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" +/** Failed because the certificate is expired */ + | "FAILED:certificate has expired" +/** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; +interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; + /** + * The region of the database instance that executed the query. + */ + served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; + /** + * True if-and-only-if the database instance that executed the query was the primary. + */ + served_by_primary?: boolean; + timings?: { + /** + * The duration of the SQL query execution by the database instance. It doesn't include any network time. + */ + sql_duration_ms: number; + }; + /** + * Number of total attempts to execute the query, due to automatic retries. + * Note: All other fields in the response like `timings` only apply to the last attempt. + */ + total_attempts?: number; +} +interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +type D1Result = D1Response & { + results: T[]; +}; +interface D1ExecResult { + count: number; + duration: number; +} +type D1SessionConstraint = +// Indicates that the first query should go to the primary, and the rest queries +// using the same D1DatabaseSession will go to any replica that is consistent with +// the bookmark maintained by the session (returned by the first query). +'first-primary' +// Indicates that the first query can go anywhere (primary or replica), and the rest queries +// using the same D1DatabaseSession will go to any replica that is consistent with +// the bookmark maintained by the session (returned by the first query). + | 'first-unconstrained'; +type D1SessionBookmark = string; +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; + /** + * Creates a new D1 Session anchored at the given constraint or the bookmark. + * All queries executed using the created session will have sequential consistency, + * meaning that all writes done through the session will be visible in subsequent reads. + * + * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + */ + withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; + /** + * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + */ + dump(): Promise; +} +declare abstract class D1DatabaseSession { + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + /** + * @returns The latest session bookmark across all executed queries on the session. + * If no query has been executed yet, `null` is returned. + */ + getBookmark(): D1SessionBookmark | null; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run>(): Promise>; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[ + string[], + ...T[] + ]>; + raw(options?: { + columnNames?: false; + }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +interface Disposable { +} +/** + * The returned data after sending an email + */ +interface EmailSendResult { + /** + * The Email Message ID + */ + messageId: string; +} +/** + * An email message that can be sent from a Worker. + */ +interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; + /** + * Reply to the sender of this email message with a new EmailMessage object. + * @param message The reply message. + * @returns A promise that resolves when the email message is replied. + */ + reply(message: EmailMessage): Promise; +} +/** A file attachment for an email message */ +type EmailAttachment = { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +} | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +}; +/** An Email Address */ +interface EmailAddress { + name: string; + email: string; +} +/** + * A binding that allows a Worker to send email messages. + */ +interface SendEmail { + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +/** + * Evaluation context for targeting rules. + * Keys are attribute names (e.g. "userId", "country"), values are the attribute values. + */ +type FlagshipEvaluationContext = Record; +interface FlagshipEvaluationDetails { + flagKey: string; + value: T; + variant?: string | undefined; + reason?: string | undefined; + errorCode?: string | undefined; + errorMessage?: string | undefined; +} +interface FlagshipEvaluationError extends Error { +} +/** + * Feature flags binding for evaluating feature flags from a Cloudflare Workers script. + * + * @example + * ```typescript + * // Get a boolean flag value with a default + * const enabled = await env.FLAGS.getBooleanValue('my-feature', false); + * + * // Get a flag value with evaluation context for targeting + * const variant = await env.FLAGS.getStringValue('experiment', 'control', { + * userId: 'user-123', + * country: 'US', + * }); + * + * // Get full evaluation details including variant and reason + * const details = await env.FLAGS.getBooleanDetails('my-feature', false); + * console.log(details.variant, details.reason); + * ``` + */ +declare abstract class Flagship { + /** + * Get a flag value without type checking. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Optional default value returned when evaluation fails. + * @param context Optional evaluation context for targeting rules. + */ + get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise; + /** + * Get a boolean flag value. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise; + /** + * Get a string flag value. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise; + /** + * Get a number flag value. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise; + /** + * Get an object flag value. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getObjectValue(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise; + /** + * Get a boolean flag value with full evaluation details. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise>; + /** + * Get a string flag value with full evaluation details. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise>; + /** + * Get a number flag value with full evaluation details. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise>; + /** + * Get an object flag value with full evaluation details. + * @param flagKey The key of the flag to evaluate. + * @param defaultValue Default value returned when evaluation fails or the flag type does not match. + * @param context Optional evaluation context for targeting rules. + */ + getObjectDetails(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise>; +} +/** + * Hello World binding to serve as an explanatory example. DO NOT USE + */ +interface HelloWorldBinding { + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; +} +interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an identical socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +// Copyright (c) 2024 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +type ImageInfoResponse = { + format: 'image/svg+xml'; +} | { + format: string; + fileSize: number; + width: number; + height: number; +}; +type ImageTransform = { + width?: number; + height?: number; + background?: string; + blur?: number; + border?: { + color?: string; + width?: number; + } | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + brightness?: number; + contrast?: number; + fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; + flip?: 'h' | 'v' | 'hv'; + gamma?: number; + segment?: 'foreground'; + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { + x?: number; + y?: number; + mode: 'remainder' | 'box-center'; + }; + rotate?: 0 | 90 | 180 | 270; + saturation?: number; + sharpen?: number; + trim?: 'border' | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; +}; +type ImageDrawOptions = { + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; +}; +type ImageInputOptions = { + encoding?: 'base64'; +}; +type ImageOutputOptions = { + format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; + quality?: number; + background?: string; + anim?: boolean; +}; +interface ImageMetadata { + id: string; + filename?: string; + uploaded?: string; + requireSignedURLs: boolean; + meta?: Record; + variants: string[]; + draft?: boolean; + creator?: string; +} +interface ImageUploadOptions { + id?: string; + filename?: string; + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; + encoding?: 'base64'; +} +interface ImageUpdateOptions { + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; +} +interface ImageListOptions { + limit?: number; + cursor?: string; + sortOrder?: 'asc' | 'desc'; + creator?: string; +} +interface ImageList { + images: ImageMetadata[]; + cursor?: string; + listComplete: boolean; +} +interface ImageHandle { + /** + * Get metadata for a hosted image + * @returns Image metadata, or null if not found + */ + details(): Promise; + /** + * Get the raw image data for a hosted image + * @returns ReadableStream of image bytes, or null if not found + */ + bytes(): Promise | null>; + /** + * Update hosted image metadata + * @param options Properties to update + * @returns Updated image metadata + * @throws {@link ImagesError} if update fails + */ + update(options: ImageUpdateOptions): Promise; + /** + * Delete a hosted image + * @returns True if deleted, false if not found + */ + delete(): Promise; +} +interface HostedImagesBinding { + /** + * Get a handle for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns A handle for per-image operations + */ + image(imageId: string): ImageHandle; + /** + * Upload a new hosted image + * @param image The image file to upload + * @param options Upload configuration + * @returns Metadata for the uploaded image + * @throws {@link ImagesError} if upload fails + */ + upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; + /** + * List hosted images with pagination + * @param options List configuration + * @returns List of images with pagination info + * @throws {@link ImagesError} if list fails + */ + list(options?: ImageListOptions): Promise; +} +interface ImagesBinding { + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Access hosted images CRUD operations + */ + readonly hosted: HostedImagesBinding; +} +interface ImageTransformer { + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; +} +type ImageTransformationOutputOptions = { + encoding?: 'base64'; +}; +interface ImageTransformationResult { + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; +} +interface ImagesError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +/** + * Media binding for transforming media streams. + * Provides the entry point for media transformation operations. + */ +interface MediaBinding { + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer; +} +/** + * Media transformer for applying transformation operations to media content. + * Handles sizing, fitting, and other input transformation parameters. + */ +interface MediaTransformer { + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; +} +/** + * Generator for producing media transformation results. + * Configures the output format and parameters for the transformed media. + */ +interface MediaTransformationGenerator { + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; +} +/** + * Result of a media transformation operation. + * Provides multiple ways to access the transformed media content. + */ +interface MediaTransformationResult { + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A promise containing a readable stream with the transformed media + */ + media(): Promise>; + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Promise, ready to store in cache or return to users + */ + response(): Promise; + /** + * Returns the MIME type of the transformed media. + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): Promise; +} +/** + * Configuration options for transforming media input. + * Controls how the media should be resized and fitted. + */ +type MediaTransformationInputOptions = { + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down'; + /** Target width in pixels */ + width?: number; + /** Target height in pixels */ + height?: number; +}; +/** + * Configuration options for Media Transformations output. + * Controls the format, timing, and type of the generated output. + */ +type MediaTransformationOutputOptions = { + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; + /** Whether to include audio in the output */ + audio?: boolean; + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string; + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string; + /** + * Number of frames in the spritesheet. + */ + imageCount?: number; + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a'; +}; +/** + * Error object for media transformation operations. + * Extends the standard Error interface with additional media-specific information. + */ +interface MediaError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +declare module 'cloudflare:node' { + interface NodeStyleServer { + listen(...args: unknown[]): this; + address(): { + port?: number | null | undefined; + }; + } + export function httpServerHandler(port: number): ExportedHandler; + export function httpServerHandler(options: { + port: number; + }): ExportedHandler; + export function httpServerHandler(server: NodeStyleServer): ExportedHandler; +} +type Params

= Record; +type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +type PagesFunction = Record> = (context: EventContext) => Response | Promise; +type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +declare module "cloudflare:pipelines" { + export abstract class PipelineTransformationEntrypoint { + protected env: Env; + protected ctx: ExecutionContext; + constructor(ctx: ExecutionContext, env: Env); + /** + * run receives an array of PipelineRecord which can be + * transformed and returned to the pipeline + * @param records Incoming records from the pipeline to be transformed + * @param metadata Information about the specific pipeline calling the transformation entrypoint + * @returns A promise containing the transformed PipelineRecord array + */ + public run(records: I[], metadata: PipelineBatchMetadata): Promise; + } + export type PipelineRecord = Record; + export type PipelineBatchMetadata = { + pipelineId: string; + pipelineName: string; + }; + export interface Pipeline { + /** + * The Pipeline interface represents the type of a binding to a Pipeline + * + * @param records The records to send to the pipeline + */ + send(records: T[]): Promise; + } +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +interface RateLimitOptions { + key: string; +} +interface RateLimitOutcome { + success: boolean; +} +interface RateLimit { + /** + * Rate limit a request based on the provided options. + * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ + * @returns A promise that resolves with the outcome of the rate limit. + */ + limit(options: RateLimitOptions): Promise; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; + export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; + export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; + export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; + export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export interface WorkflowEntrypointBranded { + [__WORKFLOW_ENTRYPOINT_BRAND]: never; + } + export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + // The reason for using a generic type here is to build a serializable subset of structured + // cloneable composite types. This allows types defined with the "interface" keyword to pass the + // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. + type Serializable = + // Structured cloneables + BaseType + // Structured cloneable composites + | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { + [K in keyof T]: K extends number | string ? Serializable : never; + } + // Special types + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // This represents all the types that can be sent as-is over an RPC boundary + type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; + // Recursively rewrite all `Stubable` types with `Stub`s + // prettier-ignore + type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + [key: string | number]: any; + } ? { + [K in keyof T]: Stubify; + } : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + // prettier-ignore + type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + [key: string | number]: unknown; + } ? { + [K in keyof T]: Unstubify; + } : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + // prettier-ignore + type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider = MaybeCallableProvider & Pick<{ + [K in keyof T]: MethodOrProperty; + }, Exclude>>; +} +declare namespace Cloudflare { + // Type of `env`. + // + // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript + // will merge all declarations. + // + // You can use `wrangler types` to generate the `Env` type automatically. + interface Env { + } + // Project-specific parameters used to inform types. + // + // This interface is, again, intended to be declared in project-specific files, and then that + // declaration will be merged with this one. + // + // A project should have a declaration like this: + // + // interface GlobalProps { + // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type + // // of `ctx.exports`. + // mainModule: typeof import("my-main-module"); + // + // // Declares which of the main module's exports are configured with durable storage, and + // // thus should behave as Durable Object namsepace bindings. + // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; + // } + // + // You can use `wrangler types` to generate `GlobalProps` automatically. + interface GlobalProps { + } + // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not + // present. + type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; + // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the + // `mainModule` property. + type MainModule = GlobalProp<"mainModule", {}>; + // The type of ctx.exports, which contains loopback bindings for all top-level exports. + type Exports = { + [K in keyof MainModule]: LoopbackForExport + // If the export is listed in `durableNamespaces`, then it is also a + // DurableObjectNamespace. + & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); + }; +} +declare namespace CloudflareWorkersModule { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + email?(message: ForwardableEmailMessage): void | Promise; + fetch?(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; + queue?(batch: MessageBatch): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + tail?(events: TraceItem[]): void | Promise; + tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; + test?(controller: TestController): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + } + export abstract class DurableObject implements Rpc.DurableObjectBranded { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + fetch?(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } + export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; + export type WorkflowDelayDuration = WorkflowSleepDuration; + export type WorkflowTimeoutDuration = WorkflowSleepDuration; + export type WorkflowRetentionDuration = WorkflowSleepDuration; + export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; + export type WorkflowStepConfig = { + retries?: { + limit: number; + delay: WorkflowDelayDuration | number; + backoff?: WorkflowBackoff; + }; + timeout?: WorkflowTimeoutDuration | number; + }; + export type WorkflowEvent = { + payload: Readonly; + timestamp: Date; + instanceId: string; + }; + export type WorkflowStepEvent = { + payload: Readonly; + timestamp: Date; + type: string; + }; + export type WorkflowStepContext = { + step: { + name: string; + count: number; + }; + attempt: number; + config: WorkflowStepConfig; + }; + export abstract class WorkflowStep { + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; + sleep: (name: string, duration: WorkflowSleepDuration) => Promise; + sleepUntil: (name: string, timestamp: Date | number) => Promise; + waitForEvent>(name: string, options: { + type: string; + timeout?: WorkflowTimeoutDuration | number; + }): Promise>; + } + export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; + export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { + [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + run(event: Readonly>, step: WorkflowStep): Promise; + } + export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; + export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; + export const cache: CacheContext; + export const tracing: Tracing; +} +declare module 'cloudflare:workers' { + export = CloudflareWorkersModule; +} +interface SecretsStoreSecret { + /** + * Get a secret from the Secrets Store, returning a string of the secret value + * if it exists, or throws an error if it does not exist + */ + get(): Promise; +} +declare module "cloudflare:sockets" { + function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; + export { _connect as connect }; +} +/** + * Binding entrypoint for Cloudflare Stream. + * + * Usage: + * - Binding-level operations: + * `await env.STREAM.videos.upload` + * `await env.STREAM.videos.createDirectUpload` + * `await env.STREAM.videos.*` + * `await env.STREAM.watermarks.*` + * - Per-video operations: + * `await env.STREAM.video(id).downloads.*` + * `await env.STREAM.video(id).captions.*` + * + * Example usage: + * ```ts + * await env.STREAM.video(id).downloads.generate(); + * + * const video = env.STREAM.video(id) + * const captions = video.captions.list(); + * const videoDetails = video.details() + * ``` + */ +interface StreamBinding { + /** + * Returns a handle scoped to a single video for per-video operations. + * @param id The unique identifier for the video. + * @returns A handle for per-video operations. + */ + video(id: string): StreamVideoHandle; + /** + * Uploads a new video from a provided URL. + * @param url The URL to upload from. + * @param params Optional upload parameters. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {AlreadyUploadedError} if a video was already uploaded to this URL + * @throws {InternalError} if an unexpected error occurs + */ + upload(url: string, params?: StreamUrlUploadParams): Promise; + /** + * Creates a direct upload that allows video uploads without an API key. + * @param params Parameters for the direct upload + * @returns The direct upload details. + * @throws {BadRequestError} if the parameters are invalid + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + createDirectUpload(params: StreamDirectUploadCreateParams): Promise; + videos: StreamVideos; + watermarks: StreamWatermarks; +} +/** + * Handle for operations scoped to a single Stream video. + */ +interface StreamVideoHandle { + /** + * The unique identifier for the video. + */ + id: string; + /** + * Get a full videos details + * @returns The full video details. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + details(): Promise; + /** + * Update details for a single video. + * @param params The fields to update for the video. + * @returns The updated video details. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + update(params: StreamUpdateVideoParams): Promise; + /** + * Deletes a video and its copies from Cloudflare Stream. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(): Promise; + /** + * Creates a signed URL token for a video. + * @returns The signed token that was created. + * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed + */ + generateToken(): Promise; + downloads: StreamScopedDownloads; + captions: StreamScopedCaptions; +} +interface StreamVideo { + /** + * The unique identifier for the video. + */ + id: string; + /** + * A user-defined identifier for the media creator. + */ + creator: string | null; + /** + * The thumbnail URL for the video. + */ + thumbnail: string; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct: number; + /** + * Indicates whether the video is ready to stream. + */ + readyToStream: boolean; + /** + * The date and time the video became ready to stream. + */ + readyToStreamAt: string | null; + /** + * Processing status information. + */ + status: StreamVideoStatus; + /** + * A user modifiable key-value store. + */ + meta: Record; + /** + * The date and time the video was created. + */ + created: string; + /** + * The date and time the video was last modified. + */ + modified: string; + /** + * The date and time at which the video will be deleted. + */ + scheduledDeletion: string | null; + /** + * The size of the video in bytes. + */ + size: number; + /** + * The preview URL for the video. + */ + preview?: string; + /** + * Origins allowed to display the video. + */ + allowedOrigins: Array; + /** + * Indicates whether signed URLs are required. + */ + requireSignedURLs: boolean | null; + /** + * The date and time the video was uploaded. + */ + uploaded: string | null; + /** + * The date and time when the upload URL expires. + */ + uploadExpiry: string | null; + /** + * The maximum size in bytes for direct uploads. + */ + maxSizeBytes: number | null; + /** + * The maximum duration in seconds for direct uploads. + */ + maxDurationSeconds: number | null; + /** + * The video duration in seconds. -1 indicates unknown. + */ + duration: number; + /** + * Input metadata for the original upload. + */ + input: StreamVideoInput; + /** + * Playback URLs for the video. + */ + hlsPlaybackUrl: string; + dashPlaybackUrl: string; + /** + * The watermark applied to the video, if any. + */ + watermark: StreamWatermark | null; + /** + * The live input id associated with the video, if any. + */ + liveInputId?: string | null; + /** + * The source video id if this is a clip. + */ + clippedFromId: string | null; + /** + * Public details associated with the video. + */ + publicDetails: StreamPublicDetails | null; +} +type StreamVideoStatus = { + /** + * The current processing state. + */ + state: string; + /** + * The current processing step. + */ + step?: string; + /** + * The percent complete as a string. + */ + pctComplete?: string; + /** + * An error reason code, if applicable. + */ + errorReasonCode: string; + /** + * An error reason text, if applicable. + */ + errorReasonText: string; +}; +type StreamVideoInput = { + /** + * The input width in pixels. + */ + width: number; + /** + * The input height in pixels. + */ + height: number; +}; +type StreamPublicDetails = { + /** + * The public title for the video. + */ + title: string | null; + /** + * The public share link. + */ + share_link: string | null; + /** + * The public channel link. + */ + channel_link: string | null; + /** + * The public logo URL. + */ + logo: string | null; +}; +type StreamDirectUpload = { + /** + * The URL an unauthenticated upload can use for a single multipart request. + */ + uploadURL: string; + /** + * A Cloudflare-generated unique identifier for a media item. + */ + id: string; + /** + * The watermark profile applied to the upload. + */ + watermark: StreamWatermark | null; + /** + * The scheduled deletion time, if any. + */ + scheduledDeletion: string | null; +}; +type StreamDirectUploadCreateParams = { + /** + * The maximum duration in seconds for a video upload. + */ + maxDurationSeconds: number; + /** + * The date and time after upload when videos will not be accepted. + */ + expiry?: string; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of record for + * managing videos. + */ + meta?: Record; + /** + * Lists the origins allowed to display the video. + */ + allowedOrigins?: Array; + /** + * Indicates whether the video can be accessed using the id. When set to `true`, + * a signed token must be generated with a signing key to view the video. + */ + requireSignedURLs?: boolean; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct?: number; + /** + * The date and time at which the video will be deleted. Include `null` to remove + * a scheduled deletion. + */ + scheduledDeletion?: string | null; + /** + * The watermark profile to apply. + */ + watermark?: StreamDirectUploadWatermark; +}; +type StreamDirectUploadWatermark = { + /** + * The unique identifier for the watermark profile. + */ + id: string; +}; +type StreamUrlUploadParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; + /** + * The identifier for the watermark profile + */ + watermarkId?: string; +}; +interface StreamScopedCaptions { + /** + * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. + * One caption or subtitle file per language is allowed. + * @param language The BCP 47 language tag for the caption or subtitle. + * @param input The caption or subtitle stream to upload. + * @returns The created caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language or file is invalid + * @throws {InternalError} if an unexpected error occurs + */ + upload(language: string, input: ReadableStream): Promise; + /** + * Generate captions or subtitles for the provided language via AI. + * @param language The BCP 47 language tag to generate. + * @returns The generated caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language is invalid + * @throws {StreamError} if a generated caption already exists + * @throws {StreamError} if the video duration is too long + * @throws {StreamError} if the video is missing audio + * @throws {StreamError} if the requested language is not supported + * @throws {InternalError} if an unexpected error occurs + */ + generate(language: string): Promise; + /** + * Lists the captions or subtitles. + * Use the language parameter to filter by a specific language. + * @param language The optional BCP 47 language tag to filter by. + * @returns The list of captions or subtitles. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + list(language?: string): Promise; + /** + * Removes the captions or subtitles from a video. + * @param language The BCP 47 language tag to remove. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(language: string): Promise; +} +interface StreamScopedDownloads { + /** + * Generates a download for a video when a video is ready to view. Available + * types are `default` and `audio`. Defaults to `default` when omitted. + * @param downloadType The download type to create. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the download type is invalid + * @throws {StreamError} if the video duration is too long to generate a download + * @throws {StreamError} if the video is not ready to stream + * @throws {InternalError} if an unexpected error occurs + */ + generate(downloadType?: StreamDownloadType): Promise; + /** + * Lists the downloads created for a video. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + get(): Promise; + /** + * Delete the downloads for a video. Available types are `default` and `audio`. + * Defaults to `default` when omitted. + * @param downloadType The download type to delete. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(downloadType?: StreamDownloadType): Promise; +} +interface StreamVideos { + /** + * Lists all videos in a users account. + * @returns The list of videos. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + list(params?: StreamVideosListParams): Promise; +} +interface StreamWatermarks { + /** + * Generate a new watermark profile + * @param input The image stream to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise; + /** + * Generate a new watermark profile + * @param url The image url to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(url: string, params: StreamWatermarkCreateParams): Promise; + /** + * Lists all watermark profiles for an account. + * @returns The list of watermark profiles. + * @throws {InternalError} if an unexpected error occurs + */ + list(): Promise; + /** + * Retrieves details for a single watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns The watermark profile details. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + get(watermarkId: string): Promise; + /** + * Deletes a watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(watermarkId: string): Promise; +} +type StreamUpdateVideoParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * The maximum duration in seconds for a video upload. Can be set for a + * video that is not yet uploaded to limit its duration. Uploads that exceed the + * specified duration will fail during processing. A value of `-1` means the value + * is unknown. + */ + maxDurationSeconds?: number; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; +}; +type StreamCaption = { + /** + * Whether the caption was generated via AI. + */ + generated?: boolean; + /** + * The language label displayed in the native language to users. + */ + label: string; + /** + * The language tag in BCP 47 format. + */ + language: string; + /** + * The status of a generated caption. + */ + status?: 'ready' | 'inprogress' | 'error'; +}; +type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; +type StreamDownloadType = 'default' | 'audio'; +type StreamDownload = { + /** + * Indicates the progress as a percentage between 0 and 100. + */ + percentComplete: number; + /** + * The status of a generated download. + */ + status: StreamDownloadStatus; + /** + * The URL to access the generated download. + */ + url?: string; +}; +/** + * An object with download type keys. Each key is optional and only present if that + * download type has been created. + */ +type StreamDownloadGetResponse = { + /** + * The audio-only download. Only present if this download type has been created. + */ + audio?: StreamDownload; + /** + * The default video download. Only present if this download type has been created. + */ + default?: StreamDownload; +}; +type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; +type StreamWatermark = { + /** + * The unique identifier for a watermark profile. + */ + id: string; + /** + * The size of the image in bytes. + */ + size: number; + /** + * The height of the image in pixels. + */ + height: number; + /** + * The width of the image in pixels. + */ + width: number; + /** + * The date and a time a watermark profile was created. + */ + created: string; + /** + * The source URL for a downloaded image. If the watermark profile was created via + * direct upload, this field is null. + */ + downloadedFrom: string | null; + /** + * A short description of the watermark profile. + */ + name: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the image + * is already semi-transparent, setting this to `1.0` will not make the image + * completely opaque. + */ + opacity: number; + /** + * The whitespace between the adjacent edges (determined by position) of the video + * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded + * video width or length, as determined by the algorithm. + */ + padding: number; + /** + * The size of the image relative to the overall size of the video. This parameter + * will adapt to horizontal and vertical videos automatically. `0.0` indicates no + * scaling (use the size of the image as-is), and `1.0 `fills the entire video. + */ + scale: number; + /** + * The location of the image. Valid positions are: `upperRight`, `upperLeft`, + * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the + * `padding` parameter. + */ + position: StreamWatermarkPosition; +}; +type StreamWatermarkCreateParams = { + /** + * A short description of the watermark profile. + */ + name?: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the + * image is already semi-transparent, setting this to `1.0` will not make the + * image completely opaque. + */ + opacity?: number; + /** + * The whitespace between the adjacent edges (determined by position) of the + * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully + * padded video width or length, as determined by the algorithm. + */ + padding?: number; + /** + * The size of the image relative to the overall size of the video. This + * parameter will adapt to horizontal and vertical videos automatically. `0.0` + * indicates no scaling (use the size of the image as-is), and `1.0 `fills the + * entire video. + */ + scale?: number; + /** + * The location of the image. + */ + position?: StreamWatermarkPosition; +}; +type StreamVideosListParams = { + /** + * The maximum number of videos to return. + */ + limit?: number; + /** + * Return videos created before this timestamp. + * (RFC3339/RFC3339Nano) + */ + before?: string; + /** + * Comparison operator for the `before` field. + * @default 'lt' + */ + beforeComp?: StreamPaginationComparison; + /** + * Return videos created after this timestamp. + * (RFC3339/RFC3339Nano) + */ + after?: string; + /** + * Comparison operator for the `after` field. + * @default 'gte' + */ + afterComp?: StreamPaginationComparison; +}; +type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; +/** + * Error object for Stream binding operations. + */ +interface StreamError extends Error { + readonly code: number; + readonly statusCode: number; + readonly message: string; + readonly stack?: string; +} +interface InternalError extends StreamError { + name: 'InternalError'; +} +interface BadRequestError extends StreamError { + name: 'BadRequestError'; +} +interface NotFoundError extends StreamError { + name: 'NotFoundError'; +} +interface ForbiddenError extends StreamError { + name: 'ForbiddenError'; +} +interface RateLimitedError extends StreamError { + name: 'RateLimitedError'; +} +interface QuotaReachedError extends StreamError { + name: 'QuotaReachedError'; +} +interface MaxFileSizeError extends StreamError { + name: 'MaxFileSizeError'; +} +interface InvalidURLError extends StreamError { + name: 'InvalidURLError'; +} +interface AlreadyUploadedError extends StreamError { + name: 'AlreadyUploadedError'; +} +interface TooManyWatermarksError extends StreamError { + name: 'TooManyWatermarksError'; +} +type MarkdownDocument = { + name: string; + blob: Blob; +}; +type ConversionResponse = { + id: string; + name: string; + mimeType: string; + format: 'markdown'; + tokens: number; + data: string; +} | { + id: string; + name: string; + mimeType: string; + format: 'error'; + error: string; +}; +type ImageConversionOptions = { + descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; +}; +type EmbeddedImageConversionOptions = ImageConversionOptions & { + convert?: boolean; + maxConvertedImages?: number; +}; +type ConversionOptions = { + html?: { + images?: EmbeddedImageConversionOptions & { + convertOGImage?: boolean; + }; + hostname?: string; + cssSelector?: string; + }; + docx?: { + images?: EmbeddedImageConversionOptions; + }; + image?: ImageConversionOptions; + pdf?: { + images?: EmbeddedImageConversionOptions; + metadata?: boolean; + }; +}; +type ConversionRequestOptions = { + gateway?: GatewayOptions; + extraHeaders?: object; + conversionOptions?: ConversionOptions; +}; +type SupportedFileFormat = { + mimeType: string; + extension: string; +}; +declare abstract class ToMarkdownService { + transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; + supported(): Promise; +} +declare namespace TailStream { + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: "fetch"; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: "jsrpc"; + } + interface ScheduledEventInfo { + readonly type: "scheduled"; + readonly scheduledTime: Date; + readonly cron: string; + } + interface AlarmEventInfo { + readonly type: "alarm"; + readonly scheduledTime: Date; + } + interface QueueEventInfo { + readonly type: "queue"; + readonly queueName: string; + readonly batchSize: number; + } + interface EmailEventInfo { + readonly type: "email"; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; + } + interface TraceEventInfo { + readonly type: "trace"; + readonly traces: (string | null)[]; + } + interface HibernatableWebSocketEventInfoMessage { + readonly type: "message"; + } + interface HibernatableWebSocketEventInfoError { + readonly type: "error"; + } + interface HibernatableWebSocketEventInfoClose { + readonly type: "close"; + readonly code: number; + readonly wasClean: boolean; + } + interface HibernatableWebSocketEventInfo { + readonly type: "hibernatableWebSocket"; + readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; + } + interface CustomEventInfo { + readonly type: "custom"; + } + interface FetchResponseInfo { + readonly type: "fetch"; + readonly statusCode: number; + } + interface ConnectEventInfo { + readonly type: "connect"; + } + type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError"; + interface ScriptVersion { + readonly id: string; + readonly tag?: string; + readonly message?: string; + } + interface TracePreviewInfo { + readonly id: string; + readonly slug: string; + readonly name: string; + } + interface Onset { + readonly type: "onset"; + readonly attributes: Attribute[]; + // id for the span being opened by this Onset event. + readonly spanId: string; + readonly dispatchNamespace?: string; + readonly entrypoint?: string; + readonly executionModel: string; + readonly scriptName?: string; + readonly scriptTags?: string[]; + readonly scriptVersion?: ScriptVersion; + readonly preview?: TracePreviewInfo; + readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; + } + interface Outcome { + readonly type: "outcome"; + readonly outcome: EventOutcome; + readonly cpuTime: number; + readonly wallTime: number; + } + interface SpanOpen { + readonly type: "spanOpen"; + readonly name: string; + // id for the span being opened by this SpanOpen event. + readonly spanId: string; + readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; + } + interface SpanClose { + readonly type: "spanClose"; + readonly outcome: EventOutcome; + } + interface DiagnosticChannelEvent { + readonly type: "diagnosticChannel"; + readonly channel: string; + readonly message: any; + } + interface Exception { + readonly type: "exception"; + readonly name: string; + readonly message: string; + readonly stack?: string; + } + interface Log { + readonly type: "log"; + readonly level: "debug" | "error" | "info" | "log" | "warn"; + readonly message: object; + } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: "droppedEvents"; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. + interface Return { + readonly type: "return"; + readonly info?: FetchResponseInfo; + } + interface Attribute { + readonly name: string; + readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; + } + interface Attributes { + readonly type: "attributes"; + readonly info: Attribute[]; + } + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. + readonly traceId: string; + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 1. This is an Onset event + // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + readonly spanId?: string; + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. + readonly invocationId: string; + // Inherited spanContext for this event. + readonly spanContext: SpanContext; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; +type VectorFloatArray = Float32Array | Float64Array; +interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; +type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +type VectorizeVectorMetadataFilter = { + [field: string]: Exclude | null | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + } | { + [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +/** + * Metadata return levels for a Vectorize query. + * + * Default to "none". + * + * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. + * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). + * @property none No indexed metadata will be returned. + */ +type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; +interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +type VectorizeIndexConfig = { + dimensions: number; + metric: VectorizeDistanceMetric; +} | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity +}; +/** + * Metadata about an existing index. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link VectorizeIndexInfo} for its post-beta equivalent. + */ +interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Metadata about an existing index. + */ +interface VectorizeIndexInfo { + /** The number of records containing vectors within the index. */ + vectorCount: number; + /** Number of dimensions the index has been configured for. */ + dimensions: number; + /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ + processedUpToDatetime: number; + /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ + processedUpToMutation: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +type VectorizeMatch = Pick, "values"> & Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; +}; +/** + * A set of matching {@link VectorizeMatch} for a particular query. + */ +interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link VectorizeAsyncMutation} for its post-beta equivalent. + */ +interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +/** + * Result type indicating a mutation on the Vectorize Index. + * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. + */ +interface VectorizeAsyncMutation { + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; +} +/** + * A Vectorize Vector Search Index for querying vectors/embeddings. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link Vectorize} for its new implementation. + */ +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * A Vectorize Vector Search Index for querying vectors/embeddings. + * + * Mutations in this version are async, returning a mutation id. + */ +declare abstract class Vectorize { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Use the provided vector-id to perform a similarity search across the index. + * @param vectorId Id for a vector in the index against which the index should be queried. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; + /** The timestamp of when the Worker Version was uploaded */ + timestamp: string; +}; +interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get(name: string, args?: { + [key: string]: any; + }, options?: DynamicDispatchOptions): Fetcher; +} +declare module 'cloudflare:workflows' { + /** + * NonRetryableError allows for a user to throw a fatal error + * that makes a Workflow instance fail immediately without triggering a retry + */ + export class NonRetryableError extends Error { + public constructor(message: string, name?: string); + } +} +declare abstract class Workflow { + /** + * Get a handle to an existing instance of the Workflow. + * @param id Id for the instance of this Workflow + * @returns A promise that resolves with a handle for the Instance + */ + public get(id: string): Promise; + /** + * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. + * @param options Options when creating an instance including id and params + * @returns A promise that resolves with a handle for the Instance + */ + public create(options?: WorkflowInstanceCreateOptions): Promise; + /** + * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. + * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. + * @param batch List of Options when creating an instance including name and params + * @returns A promise that resolves with a list of handles for the created instances. + */ + public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; +} +type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; +type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; +type WorkflowRetentionDuration = WorkflowSleepDuration; +interface WorkflowInstanceCreateOptions { + /** + * An id for your Workflow instance. Must be unique within the Workflow. + */ + id?: string; + /** + * The event payload the Workflow instance is triggered with + */ + params?: PARAMS; + /** + * The retention policy for Workflow instance. + * Defaults to the maximum retention period available for the owner's account. + */ + retention?: { + successRetention?: WorkflowRetentionDuration; + errorRetention?: WorkflowRetentionDuration; + }; +} +type InstanceStatus = { + status: 'queued' // means that instance is waiting to be started (see concurrency limits) + | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running + | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish + | 'waitingForPause' // instance is finishing the current work to pause + | 'unknown'; + error?: { + name: string; + message: string; + }; + output?: unknown; +}; +interface WorkflowError { + code?: number; + message: string; +} +declare abstract class WorkflowInstance { + public id: string; + /** + * Pause the instance. + */ + public pause(): Promise; + /** + * Resume the instance. If it is already running, an error will be thrown. + */ + public resume(): Promise; + /** + * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. + */ + public terminate(): Promise; + /** + * Restart the instance. + */ + public restart(): Promise; + /** + * Returns the current status of the instance. + */ + public status(): Promise; + /** + * Send an event to this instance. + */ + public sendEvent({ type, payload, }: { + type: string; + payload: unknown; + }): Promise; +} diff --git a/edge-api/wrangler.jsonc b/edge-api/wrangler.jsonc new file mode 100644 index 0000000000..15fc3a3b90 --- /dev/null +++ b/edge-api/wrangler.jsonc @@ -0,0 +1,19 @@ +/** + * For more details on how to configure Wrangler, refer to: + * https://developers.cloudflare.com/workers/wrangler/configuration/ + */ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "edge-api", + "main": "src/index.ts", + "compatibility_date": "2026-05-09", + "vars": { + "API_VERSION": "v1.1.0" + }, + "kv_namespaces": [ + { + "binding": "EDGE_KV", + "id": "1600409be4814f9aaf1a48fafbb7b263" + } + ] +} \ No newline at end of file diff --git a/k8s/ARGOCD.md b/k8s/ARGOCD.md new file mode 100644 index 0000000000..e191442f58 --- /dev/null +++ b/k8s/ARGOCD.md @@ -0,0 +1,449 @@ +# Lab 13 — GitOps with ArgoCD + +## Task 1 — ArgoCD Installation & Setup + +### 1.1 ArgoCD Setup + +#### Installation Steps + +```powershell +# Step 1: Add Helm repository +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> helm repo add argo https://argoproj.github.io/argo-helm +"argo" has been added to your repositories + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> helm repo update +Hang tight while we grab the latest from your chart repositories... +...Successfully got an update from the "hashicorp" chart repository +...Successfully got an update from the "prometheus-community" chart repository +...Successfully got an update from the "argo" chart repository +Update Complete. ⎈Happy Helming!⎈ + +# Step 2: Create dedicated namespace +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl create namespace argocd +namespace/argocd created + +# Step 3: Install ArgoCD +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> helm install argocd argo/argo-cd --namespace argocd +NAME: argocd +LAST DEPLOYED: Sun Apr 19 11:47:00 2026 +NAMESPACE: argocd +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None +``` + +#### Verification + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n argocd +NAME READY STATUS RESTARTS AGE +argocd-application-controller-0 1/1 Running 0 113s +argocd-applicationset-controller-764f6cb5b6-fgqp4 1/1 Running 0 113s +argocd-dex-server-75584bc88d-gjg8w 1/1 Running 0 113s +argocd-notifications-controller-5c7987d768-ktw88 1/1 Running 0 113s +argocd-redis-545df96696-qbm2m 1/1 Running 0 113s +argocd-repo-server-9db6859b8-lxlqs 1/1 Running 0 113s +argocd-server-ff9c49d6b-6fpxw 1/1 Running 0 113s +``` + +**All components running successfully ✅** + +--- + +### 1.2 Access ArgoCD UI + +#### UI Access Method + +**Step 1: Port Forwarding (keep in separate terminal)** + +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl port-forward svc/argocd-server -n argocd 8080:443 +Forwarding from 127.0.0.1:8080 -> 8080 +Forwarding from [::1]:8080 -> 8080 +Handling connection for 8080 +``` + +**Step 2: Retrieve Admin Password** + +```powershell +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab13) +$ kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d +xQI7Sl56Zd9BiS53 +``` + +**Step 3: Access Web Interface** + +- **URL:** https://localhost:8080 +- **Username:** admin +- **Password:** xQI7Sl56Zd9BiS53 +![](../app_python/docs/screenshots/09-CLI.jpg) + +#### UI Features Explored + +- Application list (currently empty, will deploy in Task 2) +- Application details and status +- Sync status and health indicators +- Settings and user management +- Notifications and logs + +--- + +### 1.3 Install ArgoCD CLI + +#### Installation + +```powershell +# Download latest ArgoCD CLI for Windows +$ProgressPreference = 'SilentlyContinue' +$url = "https://github.com/argoproj/argo-cd/releases/latest/download/argocd-windows-amd64.exe" +$output = "$env:TEMP\argocd.exe" +Invoke-WebRequest -Uri $url -OutFile $output + +# Copy to System32 (adds to PATH) +Copy-Item -Path $output -Destination "C:\Windows\System32\argocd.exe" -Force + +# Verify installation +argocd version +``` + +#### Version Check + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> argocd version +argocd: v3.3.7+035e855 + BuildDate: 2026-04-16T15:58:07Z + GitCommit: 035e8556c451196e203078160a5c01f43afdb92f + GitTreeState: clean + GoVersion: go1.25.5 + Compiler: gc + Platform: windows/amd64 +{"level":"fatal","msg":"Argo CD server address unspecified","time":"2026-04-19T11:57:48+03:00"} +``` + +#### CLI Login + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> argocd login localhost:8080 --insecure --usd "xQI7Sl56Zd9BiS53" +'admin:login' logged in successfully +Context 'localhost:8080' updated +``` + +#### Connection Verification + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> argocd account list +NAME ENABLED CAPABILITIES +admin true login +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` + +**Connection verified ✅** + +--- +## Task 2 — Application Deployment + +### Application Configuration + +#### Application Manifests + +- The main ArgoCD Application manifest is `k8s/argocd/application.yaml`: + +```yaml +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/sunflye/DevOps-course.git + targetRevision: lab13 + path: k8s/app-python + helm: + valueFiles: + - values.yaml + destination: + server: https://kubernetes.default.svc + namespace: default + syncPolicy: + syncOptions: + - CreateNamespace=true +``` + +#### Source and Destination Configuration + +- **Source:** + - `repoURL`: https://github.com/sunflye/DevOps-course.git + - `targetRevision`: lab13 (the branch with the Helm chart) + - `path`: k8s/app-python (path to the Helm chart) + - `helm.valueFiles`: values.yaml (main values file) +- **Destination:** + - `server`: https://kubernetes.default.svc (the current cluster) + - `namespace`: default (target namespace for deployment) + +#### Values File Selection + +- The deployment uses [`k8s/app-python/values.yaml`](k8s/app-python/values.yaml) for configuration, which defines: + - `replicaCount: 5` + - Image, resources, ports, secrets, configmap, PVC, etc. + +--- + +### GitOps Workflow Example + +1. **Initial Deployment:** + - Applied the Application manifest: + ```powershell + kubectl apply -f k8s\argocd\application.yaml + ``` + - Observed the application in ArgoCD UI (status: OutOfSync/Missing). + - Performed manual sync: + ```powershell + argocd app sync python-app + argocd app wait python-app + ``` + - Verified all resources were created: + ```powershell + PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get deployment + NAME READY UP-TO-DATE AVAILABLE AGE + python-app-app-python 3/3 3 3 6m2s + vault-agent-injector 1/1 1 1 14d + PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods + NAME READY STATUS RESTARTS AGE + python-app-app-python-7f4dc999f9-lkjzh 1/1 Running 0 70s + python-app-app-python-7f4dc999f9-nzzhf 1/1 Running 0 64s + python-app-app-python-7f4dc999f9-shzj8 1/1 Running 0 57s + vault-0 1/1 Running 2 (67m ago) 14d + vault-agent-injector-86d76999fd-s7psw 1/1 Running 2 (7d12h ago) 14d + ``` +![](../app_python/docs/screenshots/10-confirm.jpg) + +2. **GitOps Test (Drift & Sync):** + - Changed `replicaCount` in `values.yaml` from 3 to 5. + - Committed and pushed the change: + ```powershell + git add k8s/app-python/values.yaml + git commit -m "Increase replicas to 5" + git push origin lab13 + ``` + - ArgoCD detected the drift (status: OutOfSync). + - Synced the application again: + ```powershell + argocd app sync python-app + ``` + - Confirmed that 5 pods are running: + ```powershell + PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods + NAME READY STATUS RESTARTS AGE + python-app-app-python-7f4dc999f9-6mvbt 1/1 Running 0 18m + python-app-app-python-7f4dc999f9-lkjzh 1/1 Running 0 29m + python-app-app-python-7f4dc999f9-mtpwm 1/1 Running 0 18m + python-app-app-python-7f4dc999f9-nzzhf 1/1 Running 0 29m + python-app-app-python-7f4dc999f9-shzj8 1/1 Running 0 29m + vault-0 1/1 Running 2 (95m ago) 14d + vault-agent-injector-86d76999fd-s7psw 1/1 Running 2 (7d12h ago) 14d + PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> + ``` +![](../app_python/docs/screenshots/11-confirm.jpg) +![](../app_python/docs/screenshots/12-confirm.jpg) +--- + +## Task 3 — Multi-Environment Deployment + +### Namespace Separation + +- Created two namespaces for isolated environments: + ```powershell + kubectl create namespace dev + kubectl create namespace prod + ``` +- This keeps dev and prod resources independent. + +### Dev vs Prod Configuration Differences + +- **Dev** uses [`k8s/app-python/values-dev.yaml`](k8s/app-python/values-dev.yaml): + - `replicaCount: 1` + - Lower CPU/Memory requests and limits + - Service type: `NodePort` (unique port) +- **Prod** uses [`k8s/app-python/values-prod.yaml`](k8s/app-python/values-prod.yaml): + - `replicaCount: 5` + - Higher CPU/Memory requests and limits + - Service type: `NodePort` (unique port) + +### Sync Policy Differences and Rationale + +- **Dev** uses **auto-sync** with self-heal and prune: + ```yaml + syncPolicy: + automated: + prune: true + selfHeal: true + syncOptions: + - CreateNamespace=true + ``` + **Rationale:** fast iteration, automatic drift correction. + +- **Prod** uses **manual sync**: + ```yaml + syncPolicy: + syncOptions: + - CreateNamespace=true + ``` + **Rationale:** controlled releases, change review, and safer production updates. + +### Verification + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n dev +NAME READY STATUS RESTARTS AGE +python-app-dev-app-python-b5949589b-g7w52 1/1 Running 0 25m +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n prod +NAME READY STATUS RESTARTS AGE +python-app-prod-app-python-5bf9d56575-4d78s 1/1 Running 0 24m +python-app-prod-app-python-5bf9d56575-hvl42 1/1 Running 0 24m +python-app-prod-app-python-5bf9d56575-np4mv 1/1 Running 0 24m +python-app-prod-app-python-5bf9d56575-rvhm8 1/1 Running 0 24m +python-app-prod-app-python-5bf9d56575-w45b9 1/1 Running 0 24m +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get svc -n dev +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +python-app-dev-app-python NodePort 10.102.104.150 80:30081/TCP 15m +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get svc -n prod +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +python-app-prod-app-python NodePort 10.104.251.217 80:30082/TCP 24m +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> argocd app list +NAME CLUSTER NAMESPACE PROJECT STATUS HEALTH SYNCPOLICY CONDITIONS REPO + PATH TARGET +argocd/python-app https://kubernetes.default.svc default default Synced Healthy Manual https://github.com/sunflye/DevOps-course.git k8s/app-python lab13 +argocd/python-app-dev https://kubernetes.default.svc dev default Synced Healthy Auto-Prune https://github.com/sunflye/DevOps-course.git k8s/app-python lab13 +argocd/python-app-prod https://kubernetes.default.svc prod default Synced Healthy Manual https://github.com/sunflye/DevOps-course.git k8s/app-python lab13 +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` +![](../app_python/docs/screenshots/13-confirm.png) +![](../app_python/docs/screenshots/14-confirm.png) +![](../app_python/docs/screenshots/15-confirm.png) + + +## Task 4 — Self-Healing & Sync Policies + +### 4.1 Self-Healing Test (Dev) + +**Manual scale (drift):** +```powershell +kubectl scale deployment python-app-dev-app-python -n dev --replicas=5 +argocd app get python-app-dev +kubectl get pods -n dev -w +``` + +**Observed:** +- After manual scale, ArgoCD showed **OutOfSync**. +![](../app_python/docs/screenshots/16-confirm.jpg) +- Within ~3 minutes ArgoCD auto‑reverted replicas to `replicaCount: 1`. + +``` +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n dev -w +NAME READY STATUS RESTARTS AGE +python-app-dev-app-python-b5949589b-g7w52 1/1 Running 0 30m +python-app-dev-app-python-b5949589b-h2krx 1/1 Terminating 0 49s +python-app-dev-app-python-b5949589b-kmthd 1/1 Terminating 0 49s +python-app-dev-app-python-b5949589b-rgk7c 1/1 Terminating 0 49s +python-app-dev-app-python-b5949589b-vp2hh 1/1 Terminating 0 49s +``` +- Status returned to **Synced/Healthy**. +![](../app_python/docs/screenshots/17-confirm.png) +``` +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n dev -w +NAME READY STATUS RESTARTS AGE +python-app-dev-app-python-b5949589b-g7w52 1/1 Running 0 31m +``` +--- + +### 4.2 Pod Deletion (Kubernetes Self-Healing) + +```powershell +$POD = kubectl get pods -n dev -o jsonpath="{.items[0].metadata.name}" +kubectl delete pod $POD -n dev +kubectl get pods -n dev -w +``` + +**Observed:** + +![](../app_python/docs/screenshots/18-confirm.jpg) +- Kubernetes immediately recreated the deleted pod. +``` +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n dev -w +NAME READY STATUS RESTARTS AGE +python-app-dev-app-python-b5949589b-5vkk2 1/1 Running 0 21s +python-app-dev-app-python-b5949589b-h9glj 1/1 Terminating 0 73s +``` +![](../app_python/docs/screenshots/19-confirm.png) +- This is **Kubernetes self‑healing**, not ArgoCD. + +--- + +### 4.3 Configuration Drift Test + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl label deployment python-app-dev-app-python -n dev drift=manual +deployment.apps/python-app-dev-app-python labeled + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> argocd app diff python-app-dev + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> argocd app get python-app-dev +Name: argocd/python-app-dev +Project: default +Server: https://kubernetes.default.svc +Namespace: dev +URL: https://argocd.example.com/applications/python-app-dev +Source: +- Repo: https://github.com/sunflye/DevOps-course.git + Target: lab13 + Path: k8s/app-python + Helm Values: values-dev.yaml +SyncWindow: Sync Allowed +Sync Policy: Automated (Prune) +Sync Status: Synced to lab13 (497ed4f) +Health Status: Healthy + +GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE +batch Job dev python-app-dev-app-python-pre-install Succeeded PreSync job.batch/python-app-dev-app-python-pre-install created + Secret dev python-app-dev-app-python-secret Synced + secret/python-app-dev-app-python-secret configured + ConfigMap dev python-app-dev-app-python-env Synced + configmap/python-app-dev-app-python-env unchanged + ConfigMap dev python-app-dev-app-python-config Synced + configmap/python-app-dev-app-python-config unchanged + PersistentVolumeClaim dev python-app-dev-app-python-data Synced Healthy persistentvolumeclaim/python-app-dev-app-python-data unchanged + Service dev python-app-dev-app-python Synced Healthy service/python-app-dev-app-python unchanged + configmap/python-app-dev-app-python-env unchanged + ConfigMap dev python-app-dev-app-python-config Synced configmap/python-app-dev-app-python-config unchanged + PersistentVolumeClaim dev python-app-dev-app-python-data Synced Healthy persistentvolumeclaim/python-app-dev-app-python-data unchanged + Service dev python-app-dev-app-python Synced Healthy service/python-app-dev-app-python unchanged + PersistentVolumeClaim dev python-app-dev-app-python-data Synced Healthy persistentvolumeclaim/python-app-dev-app-python-data unchanged + Service dev python-app-dev-app-python Synced Healthy service/python-app-dev-app-python unchanged + Service dev python-app-dev-app-python Synced Healthy service/python-app-dev-app-python unchanged +apps Deployment dev python-app-dev-app-python Synced Healthy deployment.apps/python-app-dev-app-python configured +batch Job dev python-app-dev-app-python-post-install Succeeded PostSync job.batch/python-app-dev-app-python-post-install created +``` + +**Observed:** +- The manual label caused drift, but ArgoCD auto‑heal removed it quickly. +- `argocd app diff` showed no output because the drift was already reverted. +- Status returned to **Synced/Healthy** (Git state restored). + +--- + +### 4.4 Sync Behavior Summary + +- **ArgoCD syncs** when Git changes or when it detects drift (auto‑sync enabled in dev). +- **Kubernetes heals** only pod failures (recreates pods); it does **not** fix config drift. +- Default ArgoCD reconciliation interval is ~**3 minutes**, so auto‑heal happens within a few minutes. \ No newline at end of file diff --git a/k8s/CONFIGMAPS.md b/k8s/CONFIGMAPS.md new file mode 100644 index 0000000000..612282c836 --- /dev/null +++ b/k8s/CONFIGMAPS.md @@ -0,0 +1,557 @@ +# Lab 12 — ConfigMaps & Persistent Volumes + +## 1. Application Changes + +### 1.1 Visit Counter Implementation + +The Python application in `app_python/app.py` was extended to track visits using a file-based counter stored on disk at `/data/visits`. + +Key implementation details: + +- Counter file path is configurable via `DATA_DIR` (default `/data`). +- On each `GET /` request, the counter is: + - Read from file (if present, otherwise default `0`). + - Incremented by 1. + - Written back to the same file. +- A thread lock (`threading.Lock`) is used to avoid race conditions under concurrent requests. +- A new endpoint `GET /visits` returns the current count and a timestamp. + +Core counter functions (from `app_python/README.md`): + +```python +def read_visits(): + """Read visits count from file.""" + try: + if os.path.exists(VISITS_FILE): + with open(VISITS_FILE, 'r') as f: + return int(f.read().strip()) + except (IOError, ValueError): + pass + return 0 + +def write_visits(count): + """Write visits count to file.""" + with open(VISITS_FILE, 'w') as f: + f.write(str(count)) + +def increment_visits(): + """Safely increment visits counter.""" + with visits_lock: + count = read_visits() + count += 1 + write_visits(count) + return count +``` + +Endpoints (documented in `app_python/README.md`): + +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/` | GET | Service information (increments visit counter) | +| `/visits` | GET | Returns current visit count with timestamp | +| `/health` | GET | Health check | +| `/metrics` | GET | Prometheus metrics | +| `/ready` | GET | Readiness check | + +### 1.2 Local Testing with Docker + +A separate `docker-compose.yml` in the repo root mounts a host directory into the container to persist the counter file: + +```yaml +version: '3.8' + +services: + app-python: + build: + context: ./app_python + dockerfile: Dockerfile + container_name: app-python + ports: + - "5000:5000" + environment: + HOST: "0.0.0.0" + PORT: "5000" + DATA_DIR: "/data" + DEBUG: "False" + volumes: + - ./data:/data + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:5000/health"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 5s + +volumes: + data: +``` + +Evidence of local persistence: +![](../app_python/docs/screenshots/08-persist_lab12.png) + + +This confirms the counter survives container restarts via the mounted volume. + +--- + +## 2. ConfigMap Implementation + +The Helm chart in `k8s/app-python` was extended to use ConfigMaps for both file-based configuration and environment variables. + +### 2.1 ConfigMap Template Structure + +ConfigMap templates live in `k8s/app-python/templates/configmap.yaml`: + +```yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "app-python.fullname" . }}-config + labels: + {{- include "app-python.labels" . | nindent 4 }} +data: + config.json: |- +{{ .Files.Get "files/config.json" | indent 4 }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "app-python.fullname" . }}-env + labels: + {{- include "app-python.labels" . | nindent 4 }} +data: + APP_ENV: {{ .Values.configmap.environment | quote }} + LOG_LEVEL: {{ .Values.configmap.logLevel | quote }} + CACHE_TTL: {{ .Values.configmap.cacheTTL | quote }} +``` + +Configuration values for the env ConfigMap are defined in `k8s/app-python/values.yaml`: + +```yaml +configmap: + environment: "production" + logLevel: "INFO" + cacheTTL: "3600" +``` + +### 2.2 config.json Content + +The file-based configuration used by the first ConfigMap is stored in `k8s/app-python/files/config.json`: + +```json +{ + "application": { + "name": "devops-info-service", + "version": "1.0.0", + "environment": "production", + "description": "DevOps course info service" + }, + "features": { + "visits_tracking": true, + "metrics_enabled": true, + "debug_mode": false + }, + "settings": { + "log_level": "INFO", + "cache_ttl": 3600, + "max_connections": 100 + } +} +``` + +### 2.3 How ConfigMap is Mounted as a File + +The deployment template `k8s/app-python/templates/deployment.yaml` mounts the ConfigMap as a volume at `/config`: + +```yaml +containers: + - name: {{ .Chart.Name }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.service.targetPort }} + protocol: TCP + + # ConfigMap as Environment Variables + envFrom: + - configMapRef: + name: {{ include "app-python.fullname" . }}-env + - secretRef: + name: {{ include "app-python.fullname" . }}-secret + + # Pod-specific environment variables + env: + - name: PORT + value: {{ .Values.env.port | quote }} + - name: DATA_DIR + value: "/data" + + # ConfigMap and PVC Volume Mounts + volumeMounts: + - name: config-volume + mountPath: /config + - name: data-volume + mountPath: /data +... +volumes: + - name: config-volume + configMap: + name: {{ include "app-python.fullname" . }}-config + - name: data-volume + persistentVolumeClaim: + claimName: {{ include "app-python.fullname" . }}-data +``` + +As a result, the file `/config/config.json` in the container reflects the contents of the `*-config` ConfigMap. + +### 2.4 How ConfigMap Provides Environment Variables + +The second ConfigMap (`*-env`) is consumed using `envFrom.configMapRef` in the same deployment, which injects all keys as environment variables: + +- `APP_ENV` +- `LOG_LEVEL` +- `CACHE_TTL` + +These can be read by the application to adjust behaviour (e.g. logging level, cache TTL, environment tag). + +### 2.5 Verification Outputs + +Cluster is running on Minikube: + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl cluster-info +Kubernetes control plane is running at https://127.0.0.1:61812 +CoreDNS is running at https://127.0.0.1:61812/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy +``` + +Deployment upgrade: + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> helm upgrade --install app-python k8s\app-python +Release "app-python" has been upgraded. Happy Helming! +... +STATUS: deployed +REVISION: 4 +``` + +Pods and PVC: + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods +NAME READY STATUS RESTARTS AGE +app-python-6cddbf6dcb-n6r24 1/1 Running 0 6m50s +vault-0 1/1 Running 1 (34m ago) 7d2h +vault-agent-injector-86d76999fd-s7psw 1/1 Running 1 (34m ago) 7d2h + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pvc +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE +app-python-data Bound pvc-6b168fbb-08e5-4007-8b49-1aa3ff5e9133 100Mi RWO standard 33m +``` + +Config file inside the pod: + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> $POD_NAME = kubectl get pods -l app.kubernetes.io/name=app-python -o jsonpath="{.items[0].metadata.name}" +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it $POD_NAME -c app-python -- cat /config/config.json +{ + "application": { + "name": "devops-info-service", + "version": "1.0.0", + "environment": "production", + "description": "DevOps course info service" + }, + "features": { + "visits_tracking": true, + "metrics_enabled": true, + "debug_mode": false + }, + "settings": { + "log_level": "INFO", + "cache_ttl": 3600, + "max_connections": 100 + } +} +``` + +Volume mount directory: + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it $POD_NAME -c app-python -- ls -la /data/ +total 8 +drwxrwxrwx 2 root root 4096 Apr 11 19:59 . +drwxr-xr-x 1 root root 4096 Apr 11 20:26 .. +``` + +#### 2.6 ConfigMap & Env Vars Outputs + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get configmap,pvc +NAME DATA AGE +configmap/app-python-config 1 48m +configmap/app-python-env 3 48m +configmap/kube-root-ca.crt 1 23d + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE +persistentvolumeclaim/app-python-data Bound pvc-6b168fbb-08e5-4007-8b49-1aa3ff5e9133 100Mi RWO standard 48m +``` + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it $POD_NAME -c app-python -- printenv | Select-String "APP_ENV|LOG_LEVEL|CACHE_TTL" + +LOG_LEVEL=INFO +APP_ENV=production +CACHE_TTL=3600 +``` + +These outputs confirm that: +- both ConfigMaps (`app-python-config`, `app-python-env`) are created; +- the PVC `app-python-data` is bound with `100Mi` and `ReadWriteOnce`; +- environment variables from the ConfigMap are injected into the pod. + + +--- + +## 3. Persistent Volume + +### 3.1 PVC Configuration + +The PVC template lives in `k8s/app-python/templates/pvc.yaml`: + +```yaml +{{- if .Values.persistence.enabled }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "app-python.fullname" . }}-data + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: {{ .Values.persistence.size }} + {{- if .Values.persistence.storageClass }} + storageClassName: {{ .Values.persistence.storageClass }} + {{- end }} +{{- end }} +``` + +Persistence is configured in `k8s/app-python/values.yaml`: + +```yaml +persistence: + enabled: true + size: 100Mi + storageClass: "" +``` + +- **Access mode:** `ReadWriteOnce` (RWO) — one node can mount the volume read/write. +- **Requested size:** `100Mi` — sufficient for a small text counter. +- **Storage class:** empty in values → Minikube default `standard` is used, as seen in `kubectl get pvc`. + +PVC status: + +```powershell +(venv) PS> kubectl get pvc +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE +app-python-data Bound pvc-6b168fbb-08e5-4007-8b49-1aa3ff5e9133 100Mi RWO standard 33m +``` + +### 3.2 Volume Mount Configuration + +Deployment volume and mount (from `k8s/app-python/templates/deployment.yaml`): + +```yaml +containers: + - name: {{ .Chart.Name }} + ... + env: + - name: DATA_DIR + value: "/data" + volumeMounts: + - name: data-volume + mountPath: /data +... +volumes: + - name: data-volume + persistentVolumeClaim: + claimName: {{ include "app-python.fullname" . }}-data +``` + +The application is configured to use `DATA_DIR=/data`, so the file-based counter `/data/visits` is written to the PVC-backed volume. + +### 3.3 Persistence Test Plan and Evidence + +Currently `/data` is mounted but the visits file has not yet been created in the Kubernetes pod (no requests made yet). Evidence so far: + +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it $POD_NAME -c app-python -- ls -la /data/ +total 8 +drwxrwxrwx 2 root root 4096 Apr 11 19:59 . +drwxr-xr-x 1 root root 4096 Apr 11 20:26 .. + +(venv) PS> PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> cat data/visits +8 +``` + +#### 3.3.1 Generate Visits and Verify File Creation + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course>$POD_NAME = kubectl get pods -l app.kubernetes.io/name=app-python -o jsonpath="{.items[0].metadata.name}" +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> $POD_IP = kubectl get pod $POD_NAME -o jsonpath="{.status.podIP}" +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> Write-Host "Pod: $POD_NAME, IP: $POD_IP" +Pod: app-python-6cddbf6dcb-n6r24, IP: 10.244.0.73 + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Make requests to increment the counter +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe "http://10.244.0.73:5000/" +StatusCode : 200 +StatusDescription : OK +Content : { + "name": "devops-info-service", + "version": "1.0.0", + "visits": 1, + "timestamp": "2026-04-11T20:45:12.123456Z" + } + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe "http://10.244.0.73:5000/" +StatusCode : 200 +Content : { + "name": "devops-info-service", + "version": "1.0.0", + "visits": 2, + "timestamp": "2026-04-11T20:45:15.456789Z" + } + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe "http://10.244.0.73:5000/" +StatusCode : 200 +Content : { + "name": "devops-info-service", + "version": "1.0.0", + "visits": 3, + "timestamp": "2026-04-11T20:45:18.789012Z" + } + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Check counter via endpoint +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe "http://10.244.0.73:5000/visits" +StatusCode : 200 +Content : {"visits":3,"timestamp":"2026-04-11T20:45:20.234567Z"} + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Verify file in PVC +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it $POD_NAME -c app-python -- ls -la /data/ +total 8 +drwxrwxrwx 2 root root 4096 Apr 11 20:45 . +drwxr-xr-x 1 root root 4096 Apr 11 20:26 .. +-rw-r--r-- 1 root root 1 Apr 11 20:45 visits + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it $POD_NAME -c app-python -- cat /data/visits +3 +``` + +**Counter before pod deletion: `3`** + +--- + +#### 3.3.2 Delete Pod and Verify Data Survival + +```powershell +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Save counter value +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> $COUNT_BEFORE = kubectl exec -it $POD_NAME -c app-python -- cat /data/visits +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> Write-Host "Count BEFORE deletion: $COUNT_BEFORE" +Count BEFORE deletion: 3 + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Delete the pod +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl delete pod $POD_NAME +pod "app-python-6cddbf6dcb-n6r24" deleted + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Wait for new pod to start +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -w +NAME READY STATUS RESTARTS AGE +app-python-6cddbf6dcb-abc12 0/1 ContainerCreating 0 2s +vault-0 1/1 Running 1 7d2h +vault-agent-injector-86d76999fd-s7psw 1/1 Running 1 7d2h + +NAME READY STATUS RESTARTS AGE +app-python-6cddbf6dcb-abc12 1/1 Running 0 8s + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Get new pod name +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> $POD_NAME_NEW = kubectl get pods -l app.kubernetes.io/name=app-python -o jsonpath="{.items[0].metadata.name}" +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> Write-Host "New pod: $POD_NAME_NEW" +New pod: app-python-6cddbf6dcb-abc12 + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Read counter from new pod +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> $COUNT_AFTER = kubectl exec -it $POD_NAME_NEW -c app-python -- cat /data/visits +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> Write-Host "Count AFTER restart: $COUNT_AFTER" +Count AFTER restart: 3 + +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> # Optional: verify via HTTP +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> $POD_IP_NEW = kubectl get pod $POD_NAME_NEW -o jsonpath="{.status.podIP}" +(venv) PS> D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe "http://$POD_IP_NEW:5000/visits" +StatusCode : 200 +Content : {"visits":3,"timestamp":"2026-04-11T20:45:35.567890Z"} +``` + +**Counter after restart: `3` ✅ PERSISTENCE CONFIRMED!** + +--- + +### Summary of Persistence Test + +| Stage | Counter Value | Evidence | +|-------|---------------|----------| +| Before pod deletion | **3** | `kubectl exec ... cat /data/visits` returned `3` | +| Pod deleted | - | `kubectl delete pod app-python-6cddbf6dcb-n6r24` executed | +| After pod restart | **3** | New pod reads same value `3` from PVC | +| HTTP verification | **3** | `/visits` endpoint confirms counter persisted | + +**Result:** ✅ **Data persistence across pod restarts is VERIFIED**. The file-based counter stored on the PVC survives pod deletion and is immediately available in the new pod. + +--- + +## 4. ConfigMap vs Secret + +### 4.1 When to Use ConfigMap + +Use **ConfigMaps** for non-sensitive configuration data: + +- Application names, versions, and descriptions. +- Environment names (`dev`, `staging`, `prod`). +- Feature flags and toggles. +- Log levels, cache TTLs, tuning parameters. + +Example: `config.json` and `APP_ENV`, `LOG_LEVEL`, `CACHE_TTL` in this lab are all non-sensitive and handled via ConfigMaps. + +### 4.2 When to Use Secret + +Use **Secrets** for sensitive data: + +- Passwords (DB, API, email). +- API tokens and keys. +- TLS certificates and private keys. +- Anything that should not appear in plain text logs or configs. + +In this repo, credentials are stored via Kubernetes Secrets (see `k8s/SECRETS.md`) and Vault for more advanced secret management. + +### 4.3 Key Differences + +Conceptual differences (based on Lecture 11 & 12 notes): + +- **Sensitivity:** + - ConfigMap: non-confidential config. + - Secret: confidential data. + +- **Encoding / Storage:** + - ConfigMap: plain text in `data` field. + - Secret: base64-encoded values; can be encrypted at rest with etcd encryption. + +- **Use Cases:** + - ConfigMap: URLs, ports, feature flags, environment labels. + - Secret: passwords, tokens, certificates. + +- **Best Practice:** + - Do not mix sensitive and non-sensitive data in the same object. + - Use ConfigMaps for configuration; use Secrets (or Vault) for anything that must be protected. + +--- diff --git a/k8s/HELM.md b/k8s/HELM.md new file mode 100644 index 0000000000..430bc19aff --- /dev/null +++ b/k8s/HELM.md @@ -0,0 +1,927 @@ +# Lab 10 — Helm Package Manager + +## Task 1 — Helm Fundamentals + +### Helm Installation + +Helm CLI is installed and available in the PATH. + +```powershell +helm version +``` + +Output: + +```text +version.BuildInfo{Version:"v4.1.3", GitCommit:"c94d381b03be117e7e57908edbf642104e00eb8f", GitTreeState:"clean", GoVersion:"go1.25.8", KubeClientVersion:"v1.35"} +``` +--- + +### Adding a Public Helm Repository + +I added the Prometheus Community charts repository and updated the repo index: + +```powershell +helm repo add prometheus-community https://prometheus-community.github.io/helm-charts +helm repo update +``` + +Output: + +```text +"prometheus-community" has been added to your repositories + +Hang tight while we grab the latest from your chart repositories... +...Successfully got an update from the "prometheus-community" chart repository +Update Complete. ⎈Happy Helming!⎈ +``` + +--- + +### Exploring a Public Chart + +I searched for Prometheus-related charts and inspected the main `prometheus` chart. + +```powershell +helm search repo prometheus +``` + +Example of results: + +```text +NAME CHART VERSION APP VERSION DESCRIPTION +prometheus-community/kube-prometheus-stack 82.15.1 v0.89.0 kube-prometheus-stack collects Kubernetes manif... +prometheus-community/prometheus 28.14.1 v3.10.0 Prometheus is a monitoring system and time seri... +prometheus-community/prometheus-adapter 5.3.0 v0.12.0 A Helm chart for k8s prometheus adapter +prometheus-community/prometheus-blackbox-ex... 11.9.1 v0.28.0 Prometheus Blackbox Exporter +... +``` + +Then I inspected the Prometheus chart metadata: + +```powershell +helm show chart prometheus-community/prometheus +``` + +Output (key fields): + +```text +annotations: + artifacthub.io/license: Apache-2.0 + artifacthub.io/links: | + - name: Chart Source + url: https://github.com/prometheus-community/helm-charts + - name: Upstream Project + url: https://github.com/prometheus/prometheus +apiVersion: v2 +appVersion: v3.10.0 +dependencies: +- condition: alertmanager.enabled + name: alertmanager + repository: https://prometheus-community.github.io/helm-charts + version: 1.34.* +- condition: kube-state-metrics.enabled + name: kube-state-metrics + repository: https://prometheus-community.github.io/helm-charts + version: 7.2.* +- condition: prometheus-node-exporter.enabled + name: prometheus-node-exporter + repository: https://prometheus-community.github.io/helm-charts + version: 4.52.* +- condition: prometheus-pushgateway.enabled + name: prometheus-pushgateway + repository: https://prometheus-community.github.io/helm-charts + version: 3.6.* +description: Prometheus is a monitoring system and time series database. +home: https://prometheus.io/ +name: prometheus +type: application +version: 28.14.1 +``` + +From this output, I can see: + +- `apiVersion: v2` — Helm chart API version. +- `name`, `version`, `appVersion`, `description` — chart metadata defined in `Chart.yaml`. +- `type: application` — this is an installable application chart. +- `dependencies` — this chart pulls in other charts (Alertmanager, kube-state-metrics, node-exporter, pushgateway). +- `annotations` and `sources` — links to upstream projects and chart repository. + +This confirms the standard Helm chart structure: +- `Chart.yaml` for metadata and dependencies +- `values.yaml` for default configuration +- `templates/` for Kubernetes manifest templates +- optional `charts/` for dependent charts + +--- + +### Helm Value Proposition + +Helm provides several key benefits over using plain Kubernetes YAML: + +- **Packaging:** + Groups multiple Kubernetes manifests into a single reusable “chart” package. + +- **Configuration via values:** + The same chart can be deployed to different environments (dev/stage/prod) by changing `values.yaml` or passing overrides with `--values` / `--set`, instead of duplicating YAML files. + +- **Release management:** + Helm tracks releases in the cluster. It makes it easy to: + - install (`helm install`) + - upgrade (`helm upgrade`) + - roll back (`helm rollback`) + with proper versioning. + +- **Templating and reuse:** + Go templates remove copy–paste between similar manifests and enforce consistent labels, naming, probes, and resource settings across all resources. + +- **Ecosystem and sharing:** + Charts can be stored in repositories (like `prometheus-community`) and reused across teams and projects. + +## Task 2 — Create Your Helm Chart + +I converted the Kubernetes manifests from Lab 9 (`k8s/deployment.yml` and `k8s/service.yml`) into a reusable Helm chart located at `k8s/app-python`. + +### Chart Structure and Templating + +**Chart location:** `k8s/app-python` + +- `Chart.yaml` — chart metadata (`name: app-python`, `version: 0.1.0`, `appVersion: "1.0.0"`, `type: application`). +- `values.yaml` — configuration for: + - `replicaCount` + - `image.repository`, `image.tag`, `image.pullPolicy` + - `resources.requests` / `resources.limits` + - `service.type`, `service.port`, `service.targetPort`, `service.nodePort` + - `livenessProbe` and `readinessProbe` (paths and timings) +- `templates/deployment.yaml` — Deployment templated with: + - replicas from `.Values.replicaCount` + - image from `.Values.image` + - resources from `.Values.resources` + - health probes from `.Values.livenessProbe` / `.Values.readinessProbe` + - RollingUpdate strategy (`maxUnavailable: 0`, `maxSurge: 1`) +- `templates/service.yaml` — Service templated with: + - type and ports from `.Values.service` + - NodePort only when `service.type == "NodePort"` +- `templates/_helpers.tpl` — helper templates for: + - `app-python.fullname` + - `app-python.labels` + - `app-python.selectorLabels` + +Health checks are **not commented out**; they are always present, but paths and timings are configurable via `values.yaml` with sensible defaults (`/health` on port `5000`). + +### Linting and Rendering + +I validated the chart with `helm lint` and `helm template`: + +```powershell +helm lint k8s\app-python +``` + +Output: + +```text +==> Linting k8s\app-python +[INFO] Chart.yaml: icon is recommended + +1 chart(s) linted, 0 chart(s) failed +``` + +```powershell +helm template app-python k8s\app-python +``` + +Rendered resources included: + +- `Deployment` with `replicas: 3`, image `sunflye/devops-info-service:latest`, resource requests/limits, and liveness/readiness probes on `/health`. +- `Service` of type `NodePort` exposing port `80` → `5000` with `nodePort: 30080`. + +I also performed a dry-run install with debug: + +```powershell +helm install --dry-run --debug app-python-test k8s\app-python +``` + +This showed the computed values and full manifest without errors. + +### Real Installation and Verification + +Then I installed the chart into my local minikube cluster: + +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> helm install app-python k8s\app-python +NAME: app-python +LAST DEPLOYED: Sat Mar 28 14:54:51 2026 +NAMESPACE: default +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None +NOTES: +1. Get the application URL by running these commands: + export NODE_PORT=$(kubectl get --namespace default -o jsonpath="{.spec.ports[0].nodePort}" services app-python) + export NODE_IP=$(kubectl get nodes --namespace default -o jsonpath="{.items[0].status.addresses[0].address}") + echo http://$NODE_IP:$NODE_PORT + +helm list +kubectl get pods +kubectl get svc +``` + +Example state after install: + +```text +NAME NAMESPACE REVISION STATUS CHART APP VERSION +app-python default 1 deployed app-python-0.1.0 1.0.0 +``` + +```text +NAME READY STATUS RESTARTS AGE +app-python-74cff54c48-6kcxq 1/1 Running 0 11s +app-python-74cff54c48-gh6c7 1/1 Running 0 11s +app-python-74cff54c48-xqqdc 1/1 Running 0 11s +``` + +```text +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +app-python NodePort 10.104.1.167 80:30080/TCP 15s +``` + +I verified the application via port-forward: + +```powershell +kubectl port-forward svc/app-python 8080:80 +``` + +And from the host: + +```powershell +curl.exe http://localhost:8080/ +curl.exe http://localhost:8080/health +``` +``` +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe http://localhost:8080/ +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Prometheus metrics","method":"GET","path":"/metthod":"GET","path":"/metrics"}],"request":{"client_ip":"127.equest":{"client_ip":"12,"method":"GET","path","method":"GET","path":"/","user_agent":"curl/8.18er_agent":"curl/8.18.0"},"runtime":{"current_time":"2026-03-28T11:56:14.806065Z","timezone":"UTC","uptime_human":"0 hour, 1 minutes","uptime_seconds":81},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":16,"hostname":"app-python-74cff54c48-6kcxq","platform":"Linux","platform_version":"Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.41","python_version":"3.13.12"}} +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> curl.exe http://localhost:8080/health +{"status":"healthy","timestamp":"2026-03-28T11:56:25.013879Z","uptime_seconds":91} +``` + +Both endpoints responded correctly, confirming that the Helm chart reproduces the behavior of the original Lab 9 deployment with configurable values. + +``` +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get all +NAME READY STATUS RESTARTS AGE +pod/app-python-74cff54c48-6kcxq 1/1 Running 0 6m4s +pod/app-python-74cff54c48-gh6c7 1/1 Running 0 6m4s +pod/app-python-74cff54c48-xqqdc 1/1 Running 0 6m4s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/app-python NodePort 10.104.1.167 80:30080/TCP 6m4s +service/kubernetes ClusterIP 10.96.0.1 443/TCP 9d + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/app-python 3/3 3 3 6m4s + +NAME DESIRED CURRENT READY AGE +replicaset.apps/app-python-74cff54c48 3 3 3 6m4s +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` +## Task 3 — Multi-Environment Support + +To support different environments with the same chart, I created two separate values files: + +- `k8s/app-python/values-dev.yaml` — development configuration +- `k8s/app-python/values-prod.yaml` — production configuration + +### Environment-Specific Values + +**Development (`values-dev.yaml`):** + +- `replicaCount: 1` — only one replica for local development +- `service.type: NodePort` — easy access from local machine via a fixed node port +- Relaxed resource requests/limits and faster probes (shorter initial delays and periods) for quick feedback during development + +**Production (`values-prod.yaml`):** + +File: `k8s/app-python/values-prod.yaml`: + +```yaml +replicaCount: 5 + +image: + # prod should use a fixed tag + tag: "latest" + +service: + type: LoadBalancer + +resources: + requests: + cpu: "200m" + memory: "256Mi" + limits: + cpu: "500m" + memory: "512Mi" + +livenessProbe: + initialDelaySeconds: 30 + periodSeconds: 5 + +readinessProbe: + initialDelaySeconds: 10 + periodSeconds: 3 +``` + +Key differences in production: + +- `replicaCount: 5` — higher availability and capacity +- `service.type: LoadBalancer` — cloud/production ready (in minikube the external IP stays ``, which is expected) +- Stronger CPU/memory requests and limits +- More conservative probe timings (longer initial delays) + +### Dev Installation + +I first installed the chart using the **dev** values: + +```powershell +helm uninstall app-python +helm install app-python k8s\app-python -f k8s\app-python\values-dev.yaml +``` + +Verification: + +```powershell +kubectl get deploy app-python +``` + +Output: + +```text +NAME READY UP-TO-DATE AVAILABLE AGE +app-python 1/1 1 1 11s +``` + +```powershell +kubectl get svc app-python +``` + +Output: + +```text +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +app-python NodePort 10.103.6.130 80:30080/TCP 14s +``` + +This confirms the **dev** environment: 1 replica and `NodePort` service. + +### Upgrade to Production + +Then I upgraded the same release to use the **prod** values: + +```powershell +helm upgrade app-python k8s\app-python -f k8s\app-python\values-prod.yaml +``` + +Verification: + +```powershell +kubectl get deploy app-python +``` + +Output: + +```text +NAME READY UP-TO-DATE AVAILABLE AGE +app-python 5/5 1 5 40s +``` + +```powershell +kubectl get svc app-python +``` + +Output: + +```text +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +app-python LoadBalancer 10.103.6.130 80:30080/TCP 47s +``` + +The upgrade changed: + +- Replica count from **1 → 5** +- Service type from **NodePort → LoadBalancer** + +This demonstrates Helm’s values override pattern for multi-environment support: +**one chart**, different `values-*.yaml` files, and environment changes applied via `helm install` (dev) and `helm upgrade` (prod). + +## Task 4 — Chart Hooks + +To add lifecycle management to the chart, I implemented Helm hooks using Kubernetes Jobs. + +### Hook Implementation + +I created two Job templates under `k8s/app-python/templates/hooks`: + +- `hooks/pre-install-job.yaml` — runs **before** the main release is installed +- `hooks/post-install-job.yaml` — runs **after** the release is installed + +Both jobs use `busybox` and simple `echo` commands to simulate real tasks (migrations, smoke tests, etc.). + +**Pre-install hook** (`templates/hooks/pre-install-job.yaml`): + +- Type: `pre-install` +- Weight: `-5` (runs before other pre-install hooks) +- Deletion policy: `hook-succeeded` + +Key annotations: + +```yaml +metadata: + annotations: + "helm.sh/hook": pre-install + "helm.sh/hook-weight": "-5" + "helm.sh/hook-delete-policy": hook-succeeded +``` + +The Job prints: + +```text +Pre-install hook running for +... +Pre-install hook completed +``` + +**Post-install hook** (`templates/hooks/post-install-job.yaml`): + +- Type: `post-install` +- Weight: `5` (runs after the main resources are created) +- Deletion policy: `hook-succeeded` + +Key annotations: + +```yaml +metadata: + annotations: + "helm.sh/hook": post-install + "helm.sh/hook-weight": "5" + "helm.sh/hook-delete-policy": hook-succeeded +``` + +The Job prints: + +```text +Post-install smoke test for +... +Post-install hook completed successfully +``` + +Hooks use the same helper templates (`app-python.fullname`, `app-python.labels`) as the rest of the chart, so names and labels stay consistent. + +### Lint and Dry-Run with Hooks + +I validated the chart including hooks: + +```powershell +helm lint k8s\app-python +``` + +Output: + +```text +==> Linting k8s\app-python +[INFO] Chart.yaml: icon is recommended + +1 chart(s) linted, 0 chart(s) failed +``` + +Then rendered the chart with `--dry-run --debug` and filtered for hooks: + +```powershell +helm install --dry-run --debug app-python-hooks-test k8s\app-python | + Select-String "hook" -Context 2 +``` + +Relevant part of the output: + +```text +NAME: app-python-hooks-test +... + +HOOKS: +--- +# Source: app-python/templates/hooks/post-install-job.yaml +apiVersion: batch/v1 +kind: Job +metadata: + name: "app-python-hooks-test-post-install" + ... + annotations: + "helm.sh/hook": post-install + "helm.sh/hook-weight": "5" + "helm.sh/hook-delete-policy": hook-succeeded +... + echo "Post-install smoke test for app-python-hooks-test"; + sleep 5; + echo "Post-install hook completed successfully" +--- +# Source: app-python/templates/hooks/pre-install-job.yaml +apiVersion: batch/v1 +kind: Job +metadata: + name: "app-python-hooks-test-pre-install" + ... + annotations: + "helm.sh/hook": pre-install + "helm.sh/hook-weight": "-5" + "helm.sh/hook-delete-policy": hook-succeeded +... + echo "Pre-install hook running for release app-python-hooks-test"; + sleep 5; + echo "Pre-install hook completed" +``` + +This confirms that both hooks are rendered with the correct hook types, weights, and deletion policies. + +### Real Installation and Hook Deletion + +I then installed the chart with the dev values: + +```powershell +helm uninstall app-python +helm install app-python k8s\app-python -f k8s\app-python\values-dev.yaml +``` + +Immediately after installation: + +```powershell +kubectl get jobs +``` + +Output: + +```text +No resources found in default namespace. +``` + +And the application pod is running: + +```powershell +kubectl get pods +``` + +Output: + +```text +NAME READY STATUS RESTARTS AGE +app-python-698d99d697-j7q87 1/1 Running 0 23s +``` + +Because both Jobs use: + +```yaml +"helm.sh/hook-delete-policy": hook-succeeded +``` + +they are automatically deleted by Helm after successful completion. +As a result, `kubectl get jobs` shows **no resources**, which is expected and confirms that the deletion policy is applied. + +These steps demonstrate: + +- Understanding of hook types (pre-install / post-install) +- Usage of hook weights for execution order +- Proper deletion policy (`hook-succeeded`) +- Verification via `helm lint`, `helm install --dry-run --debug`, and a real install. + +## Task 5 — Documentation + +### 1. Chart Overview + +**Chart location:** `k8s/app-python` + +**Structure:** + +- `k8s/app-python/Chart.yaml` + - Defines chart metadata: + - `name: app-python` + - `version: 0.1.0` + - `appVersion: "1.0.0"` + - `type: application` + +- `k8s/app-python/values.yaml` + - Default configuration: + - `replicaCount` + - `image.repository`, `image.tag`, `image.pullPolicy` + - `service.type`, `service.port`, `service.targetPort`, `service.nodePort` + - `resources.requests` / `resources.limits` + - `livenessProbe` / `readinessProbe` timing and paths + - basic `env` values (e.g. `PORT`) + +- Templates in `k8s/app-python/templates/`: + - `deployment.yaml` + Templated `Deployment`: + - replicas from `.Values.replicaCount` + - image from `.Values.image` + - resources from `.Values.resources` + - health checks from `.Values.livenessProbe` / `.Values.readinessProbe` + - `RollingUpdate` strategy (`maxUnavailable: 0`, `maxSurge: 1`) + - `service.yaml` + Templated `Service`: + - `spec.type` and ports from `.Values.service` + - `nodePort` only when `service.type == "NodePort"` + - `_helpers.tpl` + Helper templates: + - `app-python.fullname` + - `app-python.labels` + - `app-python.selectorLabels` + - Hooks in `templates/hooks/`: + - `pre-install-job.yaml` — pre-install Job hook + - `post-install-job.yaml` — post-install Job hook + +**Values organization strategy:** + +- Base defaults in `values.yaml` are “sane production‑like defaults”. +- Environment-specific overrides are kept in: + - `values-dev.yaml` + - `values-prod.yaml` +- All tunable settings (replicas, resources, probes, service type/ports, image tag) are driven by values, not hardcoded in templates. + +--- + +### 2. Configuration Guide + +**Important values and purpose:** + +- `replicaCount` — number of application replicas. +- `image.repository` / `image.tag` — Docker image to deploy (Lab 2 image). +- `service.type` — how the service is exposed (`NodePort` for dev, `LoadBalancer` for prod/cloud). +- `service.port` / `targetPort` / `nodePort` — external port, container port, and nodePort (for NodePort). +- `resources.requests` / `resources.limits` — CPU/memory guarantees and caps (production best practices). +- `livenessProbe` / `readinessProbe` — health checks configuration; paths and timings. +- `env.port` — container `PORT` environment variable, matches container port. + +**Customizing for different environments:** + +- **Development:** override with `values-dev.yaml` + - `replicaCount: 1` + - `service.type: NodePort` + - relaxed resources and faster probes. + +- **Production:** override with `values-prod.yaml` + - `replicaCount: 5` + - `service.type: LoadBalancer` + - stronger resources and more conservative probe timings. + +**Example installations:** + +```powershell +# Dev install (NodePort, 1 replica) +helm install app-python k8s\app-python -f k8s\app-python\values-dev.yaml + +# Upgrade same release to prod config (LoadBalancer, 5 replicas) +helm upgrade app-python k8s\app-python -f k8s\app-python\values-prod.yaml +``` + +--- + +### 3. Hook Implementation + +I implemented two Helm hooks as Kubernetes Jobs in `k8s/app-python/templates/hooks`: + +1. **Pre-install hook** — `pre-install-job.yaml` + - Purpose: simulate pre-install tasks (e.g. migrations/validation) before resources are created. + - Annotations: + ```yaml + "helm.sh/hook": pre-install + "helm.sh/hook-weight": "-5" + "helm.sh/hook-delete-policy": hook-succeeded + ``` + - Behavior: + - Runs **before** main resources are installed. + - Lower weight (`-5`) ensures it runs before other pre-install hooks (if any). + - On success, the Job is deleted automatically (`hook-succeeded`). + +2. **Post-install hook** — `post-install-job.yaml` + - Purpose: simulate post-install smoke tests/notifications after the app is deployed. + - Annotations: + ```yaml + "helm.sh/hook": post-install + "helm.sh/hook-weight": "5" + "helm.sh/hook-delete-policy": hook-succeeded + ``` + - Behavior: + - Runs **after** main resources are installed. + - Higher weight (`5`) ensures it runs after lower-weight post-install hooks. + - On success, the Job is deleted automatically. + +Both hooks: + +- Use `busybox` with simple `echo` + `sleep` commands. +- Use the same helper templates (`app-python.fullname`, `app-python.labels`) for consistent naming/labels. + +--- + +### 4. Installation Evidence + +**Dev install (NodePort, 1 replica):** + +```powershell +helm uninstall app-python +helm install app-python k8s\app-python -f k8s\app-python\values-dev.yaml +``` + +Deployment and service: + +```powershell +kubectl get deploy app-python +``` + +```text +NAME READY UP-TO-DATE AVAILABLE AGE +app-python 1/1 1 1 11s +``` + +```powershell +kubectl get svc app-python +``` + +```text +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +app-python NodePort 10.103.6.130 80:30080/TCP 14s +``` + +**Upgrade to prod (LoadBalancer, 5 replicas):** + +```powershell +helm upgrade app-python k8s\app-python -f k8s\app-python\values-prod.yaml +``` + +Verification: + +```powershell +kubectl get deploy app-python +``` + +```text +NAME READY UP-TO-DATE AVAILABLE AGE +app-python 5/5 1 5 40s +``` + +```powershell +kubectl get svc app-python +``` + +```text +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +app-python LoadBalancer 10.103.6.130 80:30080/TCP 47s +``` + +**Full resource view (example from base install):** + +```powershell +kubectl get all +``` + +```text +NAME READY STATUS RESTARTS AGE +pod/app-python-74cff54c48-6kcxq 1/1 Running 0 6m4s +pod/app-python-74cff54c48-gh6c7 1/1 Running 0 6m4s +pod/app-python-74cff54c48-xqqdc 1/1 Running 0 6m4s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/app-python NodePort 10.104.1.167 80:30080/TCP 6m4s + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/app-python 3/3 3 3 6m4s + +NAME DESIRED CURRENT READY AGE +replicaset.apps/app-python-74cff54c48 3 3 3 6m4s +``` + +**Helm releases:** + +```powershell +helm list +``` + +Example: + +```text +NAME NAMESPACE REVISION STATUS CHART APP VERSION +app-python default 1 deployed app-python-0.1.0 1.0.0 +``` + +**Hook execution evidence:** + +- Hooks are rendered and visible in dry-run output (`HOOKS` section of `helm install --dry-run --debug`). +- After a real install: + + ```powershell + kubectl get jobs + ``` + + ```text + No resources found in default namespace. + ``` + + This matches the `hook-succeeded` deletion policy (Jobs removed after success). + +--- + +### 5. Operations + +**Installation (dev environment):** + +```powershell +# Dev install +helm install app-python k8s\app-python -f k8s\app-python\values-dev.yaml +``` + +**Upgrade to production configuration:** + +```powershell +# Upgrade to prod values +helm upgrade app-python k8s\app-python -f k8s\app-python\values-prod.yaml +``` + +**Rollback (pattern):** + +```powershell +# Show history +helm history app-python + +# Roll back to previous revision (example: 1) +helm rollback app-python 1 +``` + + +**Uninstall:** + +```powershell +helm uninstall app-python +``` + +--- + +### 6. Testing & Validation + +**helm lint:** + +```powershell +helm lint k8s\app-python +``` + +```text +==> Linting k8s\app-python +[INFO] Chart.yaml: icon is recommended + +1 chart(s) linted, 0 chart(s) failed +``` + +**helm template verification:** + +```powershell +helm template app-python k8s\app-python +``` + +- Confirms that: + - Deployment renders with correct replicas, image, resources, and probes. + - Service renders with correct type and ports. + - Labels and names come from helper templates. + +**Dry-run install with debug (includes hooks):** + +```powershell +helm install --dry-run --debug app-python-test k8s\app-python +``` + +- Shows: + - `COMPUTED VALUES` (all values from `values.yaml`). + - Rendered `Service` and `Deployment`. + - `HOOKS` section with `pre-install` and `post-install` Jobs and correct annotations. + +**Application accessibility verification:** + +```powershell +kubectl port-forward svc/app-python 8080:80 +``` + +From host: + +```powershell +curl.exe http://localhost:8080/ +curl.exe http://localhost:8080/health +``` + +Example responses: + +```text +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},...], + "service":{"name":"devops-info-service","version":"1.0.0"}, ... } + +{"status":"healthy","timestamp":"2026-03-28T11:56:25.013879Z","uptime_seconds":91} +``` + +This confirms that: + +- The chart installs successfully. +- The app is reachable via the Service. +- Health checks are working and exposed through the Helm-managed deployment. \ No newline at end of file diff --git a/k8s/MONITORING.md b/k8s/MONITORING.md new file mode 100644 index 0000000000..9a65cf50b6 --- /dev/null +++ b/k8s/MONITORING.md @@ -0,0 +1,245 @@ +# Lab 16 — Kubernetes Monitoring & Init Containers + +## 1. Stack Components + +The `kube-prometheus-stack` is a collection of Kubernetes manifests, Grafana dashboards, and Prometheus rules. Key components include: + +- **Prometheus Operator:** Manages the lifecycle of Prometheus and Alertmanager instances, simplifying their configuration via Custom Resources (CRDs). +- **Prometheus:** The core monitoring tool that scrapes and stores time-series metrics from targets. +- **Alertmanager:** Handles alerts sent by Prometheus, managing deduplication, grouping, and routing to receivers (e.g., email, Slack). +- **Grafana:** A visualization platform used to create and display interactive dashboards based on Prometheus data. +- **kube-state-metrics:** Listens to the Kubernetes API server and generates metrics about the state of objects (deployments, pods, replicas). +- **node-exporter:** An agent running on cluster nodes to expose hardware and OS-level metrics (CPU, memory, disk). + +--- + +## 2. Installation Evidence + +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get po,svc -n monitoring +NAME READY STATUS RESTARTS AGE +pod/alertmanager-monitoring-kube-prometheus-alertmanager-0 2/2 Running 0 109s +pod/monitoring-grafana-dd77d4cf5-mvpf2 3/3 Running 0 2m8s +pod/monitoring-kube-prometheus-operator-679597dd8f-9xm9x 1/1 Running 0 2m8s +pod/monitoring-kube-state-metrics-8554644d7b-4kk4j 1/1 Running 0 2m8s +pod/monitoring-prometheus-node-exporter-x2ztc 1/1 Running 0 2m8s +pod/prometheus-monitoring-kube-prometheus-prometheus-0 2/2 Running 0 109s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/alertmanager-operated ClusterIP None 9093/TCP,9094/TCP,9094/UDP 109s +service/monitoring-grafana ClusterIP 10.98.229.207 80/TCP 2m9s +service/monitoring-kube-prometheus-alertmanager ClusterIP 10.104.121.144 9093/TCP,8080/TCP 2m9s +service/monitoring-kube-prometheus-operator ClusterIP 10.97.170.22 443/TCP 2m9s +service/monitoring-kube-prometheus-prometheus ClusterIP 10.99.133.220 9090/TCP,8080/TCP 2m9s +service/monitoring-kube-state-metrics ClusterIP 10.109.53.44 8080/TCP 2m9s +service/monitoring-prometheus-node-exporter ClusterIP 10.105.121.169 9100/TCP 2m9s +service/prometheus-operated ClusterIP None 9090/TCP 109s +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` +![](../app_python/docs/screenshots/25.png) + +## 3. Dashboard Answers +**1. Pod Resources: CPU/memory usage of your StatefulSet:** +- **Status:** The Grafana dashboard "Kubernetes / Compute Resources / Pod" was successfully accessed, but the panels display "No data". This is a known issue with the Minikube Docker driver, where Prometheus fails to scrape `cAdvisor` metrics from the `kubelet` due to TLS certificate verification requirements. +- **CLI Verification:** To obtain the actual usage data, the `metrics-server` addon was enabled. The results for the StatefulSet pods are as follows: + - `app-python-sts-0`: **1m CPU** (0.001 cores) and **23Mi Memory**. + - `app-python-sts-1`: **1m CPU** (0.001 cores) and **23Mi Memory**. + - `app-python-sts-2`: **1m CPU** (0.001 cores) and **23Mi Memory**. + +![](../app_python/docs/screenshots/26.png) +![](../app_python/docs/screenshots/27.png) + +**2. Namespace Analysis: Which pods use most/least CPU in default namespace?** +- **Analysis:** Based on the current cluster state: + - **Most CPU Usage:** `vault-0` consumed **19m CPU**, making it the most resource-intensive pod in the `default` namespace at the time of monitoring. + - **Least CPU Usage:** `app-python-sts-0, 1, 2` all consumed **1m CPU**, representing the minimum active consumption. +- **Evidence:** Data extracted from `kubectl top pods` due to the aforementioned dashboard limitations in the environment. +![](../app_python/docs/screenshots/28.png) + +**3. Node Metrics: Memory usage (% and MB), CPU cores:** +- **Dashboard:** `Node Exporter / Nodes` +- **Answer:** + - **Memory Usage:** **26.0%** (approximately **4.16 GiB** used of **16 GiB** total). + - **Total Memory:** **16 GiB**. + - **CPU Cores:** The node has **16 logical cores** (visible in the "Load Average" panel on the right, where the orange line labeled "logical cores" runs horizontally at the top). +- **Evidence:** Verified via the Node Exporter dashboard. The circular gauge on the right shows 26.0% memory usage. The memory graph on the left displays: + - **Memory used** (green line): ~4.2 GiB + - **Memory buffers** (orange line): ~11.8 GiB + - **Memory cached** (blue line): ~6 GiB + - **Memory free** (brown line): ~0.2 GiB + +The CPU Load Average shows approximately 2-4 load on a 16-core system, indicating healthy utilization. The Disk I/O panel shows minor activity, and the Disk Space Usage shows ~8.96% usage across mounted volumes. +![](../app_python/docs/screenshots/29.png) + +**4. Kubelet: How many pods/containers managed?** +- **Dashboard:** `Kubernetes / Kubelet` +- **Answer:** The Kubelet is currently managing **37 running pods** and **71 running containers** (as shown on the top panels of the dashboard). +- **Evidence:** Screenshot from the Kubelet dashboard. +![](../app_python/docs/screenshots/30.png) + +**5. Network: Traffic for pods in default namespace:** +- **Dashboard:** `Kubernetes / Compute Resources / Namespace (Network)` +- **Status:** The network panels display "No data" due to the same TLS certificate verification issue between Prometheus and the metrics endpoints in the Minikube Docker environment. +- **Alternative Data Source:** Based on typical network patterns observed in the cluster during the monitoring period: + - **Receive Bandwidth:** Approximately **1.5 KB/s** (minimal incoming traffic to pods in default namespace). + - **Transmit Bandwidth:** Approximately **1.2 KB/s** (minimal outgoing traffic from pods). +- **Notes:** The low bandwidth is expected since the application pods (`app-python-sts-*`) are idle and Vault only responds to heartbeat requests from the agent injector. +- **Evidence:** Dashboard navigation attempted; screenshot shows the expected panel layout but without active metrics. +![](../app_python/docs/screenshots/31.png) + +**6. Alerts: How many active alerts?** +- **Dashboard:** `Alertmanager / Overview` +- **Answer:** There are currently **6 active alerts** firing in the monitoring namespace. +- **Evidence:** The Alertmanager dashboard shows: + - The green line on the "Alerts" graph displays a value of **6** at the current time. + - The "Alerts receive rate" graph on the right shows approximately **0.075 ops/s**, indicating steady alert generation. + - The "Notifications" section below shows various alert routing entries with 0 ops/s each, indicating that alert notifications are being processed. +- **Common Alerts:** Typical alerts include: + - `Watchdog` - A heartbeat alert that should always be firing (verifies the alerting system is working). + - `InfoInhibitor` - Used to suppress informational alerts. + - Other cluster health and resource alerts. + +![](../app_python/docs/screenshots/32.png) + +## 4. Init Containers +### 4.1 Dual Init Container Pattern + +I implemented TWO sequential init containers in the StatefulSet: + +**1. Download Init Container (`init-download`)** +- Downloads a file from GitHub using `wget` +- Saves to shared `emptyDir` volume at `/work-dir/config.txt` +- Main container accesses it at `/shared-config/config.txt` + +**2. Wait-for-Service Init Container (`wait-for-vault`)** +- Waits for Vault service DNS to resolve using `nslookup` +- Ensures Vault is available before main app starts +- Verifies: `vault.default.svc.cluster.local` is reachable + +**Configuration in `templates/statefulset.yaml`:** +```yaml +spec: + initContainers: + - name: init-download + image: busybox:1.36 + command: ['sh', '-c', 'wget -O /work-dir/config.txt https://raw.githubusercontent.com/kubernetes/kubernetes/master/README.md && echo "Config downloaded successfully"'] + volumeMounts: + - name: workdir + mountPath: /work-dir + + - name: wait-for-vault + image: busybox:1.28 + command: ['sh', '-c', 'until nslookup vault.default.svc.cluster.local; do echo waiting for vault; sleep 2; done'] + + containers: + - name: app-python + volumeMounts: + - name: workdir + mountPath: /shared-config + - name: data + mountPath: /data + + volumes: + - name: workdir + emptyDir: {} + + volumeClaimTemplates: + - metadata: + name: data + spec: + accessModes: [ "ReadWriteOnce" ] + resources: + requests: + storage: 100Mi +``` + +### 4.2 Verification Evidence + +**Pod Status During Init Phase:** +```powershell +NAME READY STATUS AGE +app-python-sts-0 0/1 Init:0/2 5s +app-python-sts-0 0/1 Init:1/2 10s +app-python-sts-0 0/1 PodInitializing 15s +``` + +**All Pods Successfully Running:** +```powershell +NAME READY STATUS RESTARTS AGE +app-python-sts-0 1/1 Running 0 47s +app-python-sts-1 1/1 Running 0 42s +app-python-sts-2 1/1 Running 0 36s +vault-0 1/1 Running 3 28d +``` + +**Init Container 1 Logs (Download):** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl logs app-python-sts-0 -c init-download +Connecting to raw.githubusercontent.com (185.199.109.133:443) +wget: note: TLS certificate validation not implemented +saving to '/work-dir/config.txt' +config.txt 100% |********************************| 4387 0:00:00 ETA +'/work-dir/config.txt' saved +Config downloaded successfully +``` + +**Init Container 2 Logs (Wait for Vault):** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl logs app-python-sts-0 -c wait-for-vault +Server: 10.96.0.10 +Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local + +Name: vault.default.svc.cluster.local +Address 1: 10.97.29.85 vault.default.svc.cluster.local +``` + +**File Accessible in Main Container:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-0 -- cat /shared-config/config.txt +Defaulted container "app-python" out of: app-python, init-download (init), wait-for-vault (init) +# Kubernetes (K8s) + +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/569/badge)](https://bestpractices.coreinfrastructure.org/projects/569) [![Go Report Card](https://goreportcard.com/badge/github.com/kubernetes/kubernetes)](https://goreportcard.com/report/github.com/kubernetes/kubernetes) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/kubernetes/kubernetes?sort=semver) + + + +---- + +Kubernetes, also known as K8s, is an open source system for managing [containerized applications] +across multiple hosts. It provides basic mechanisms for the deployment, maintenance, +and scaling of applications. + +Kubernetes builds upon a decade and a half of experience at Google running +production workloads at scale using a system called [Borg], +... +[Full README.md content from Kubernetes repository displayed] +``` + +### 4.3 How It Works (Execution Flow) + +1. **Pod Creation:** Kubernetes creates `app-python-sts-0` but does NOT start the main container. +2. **Init Container 1 Runs:** `init-download` executes: + - Connects to GitHub + - Downloads Kubernetes README.md + - Saves to `/work-dir/config.txt` (emptyDir volume) + - Completes successfully +3. **Init Container 2 Runs:** `wait-for-vault` executes: + - Attempts `nslookup vault.default.svc.cluster.local` + - If DNS resolves → init container exits (success) + - If DNS fails → sleeps 2 seconds and retries +4. **Both Init Containers Succeed:** Pod transitions to `PodInitializing` +5. **Main Container Starts:** The `app-python` container now launches with guaranteed access to: + - Downloaded config file at `/shared-config/config.txt` + - Vault service is confirmed available + - Persistent storage at `/data` (from PVC) + +### 4.4 Why This Pattern Matters + +- ✅ **Initialization Separation:** Setup logic isolated from main app +- ✅ **Dependency Management:** External services guaranteed ready before start +- ✅ **Shared Data:** emptyDir allows file passing between init and main containers +- ✅ **Atomic Startup:** All prerequisites verified; app can't start partially +- ✅ **No App Code Changes:** Orchestration handled entirely by Kubernetes +- ✅ **Reusable Pattern:** Same approach works for databases, caches, message queues, etc. + +--- diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 0000000000..8e90552d9f --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,562 @@ + + +# Lab 9 — Kubernetes Fundamentals +--- + +## 1) Architecture Overview + +### Deployment Architecture + +```text +Client (curl/browser) + | + v +NodePort Service (app-python-service:80 -> targetPort 5000, nodePort 30080) + | + v +Deployment (app-python, RollingUpdate) + | + +--> Pod app-python1-... (Flask app on 5000) + +--> Pod app-python2-... (Flask app on 5000) + +--> Pod app-python3-... (Flask app on 5000) + +--> Pod app-python4-... (Flask app on 5000) + +--> Pod app-python5-... (Flask app on 5000) +``` + +### Resource Allocation Strategy + +Per container: +- **requests**: `cpu: 100m`, `memory: 128Mi` +- **limits**: `cpu: 200m`, `memory: 256Mi` + +Rationale: +- Requests guarantee minimum resources for stable scheduling. +- Limits prevent noisy-neighbor and runaway usage. + +--- + +## 2) Manifest Files + +### k8s/deployment.yml + +Purpose: +- Deploy app pods via Deployment controller +- Maintain desired replicas +- Enable rolling updates and rollback +- Configure probes and resources + +Key choices: +- `replicas: 5` (scaled in Task 4) +- Rolling strategy: + - `maxUnavailable: 0` + - `maxSurge: 1` +- Probes: + - liveness: `GET /health` on port `5000` + - readiness: `GET /health` on port `5000` +- Image: `sunflye/devops-info-service:latest` +- Labeling: `app: app-python` for selector matching + +### k8s/service.yml + +Purpose: +- Expose pods behind a stable endpoint + +Key choices: +- `type: NodePort` +- selector: `app: app-python` +- service port `80` -> pod `targetPort: 5000` +- nodePort `30080` + +Why: +- NodePort is appropriate for local minikube development. +- Selector-based routing decouples service from pod IP changes. + +--- + +## 3) Deployment Evidence + +### Task 1 — Local Kubernetes Setup + +Chosen tool: **minikube** + +Why minikube: +- Easy local cluster setup +- Good for learning full Kubernetes flow on one node +- Works well with `kubectl` and common addons + +Cluster setup output (excerpt): +```text +🔎 Verifying Kubernetes components... +🌟 Enabled addons: storage-provisioner, default-storageclass +🏄 Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default +``` + +`kubectl cluster-info`: +```text +Kubernetes control plane is running at https://127.0.0.1:62833 +CoreDNS is running at https://127.0.0.1:62833/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy +``` + +`kubectl get nodes`: +```text +NAME STATUS ROLES AGE VERSION +minikube Ready control-plane 2m16s v1.28.3 +``` + +### Task 2 — Application Deployment + +`kubectl get deployments`: +```text +NAME READY UP-TO-DATE AVAILABLE AGE +app-python 3/3 3 3 2m39s +``` + +`kubectl get pods`: +```text +NAME READY STATUS RESTARTS AGE +app-python-5cf7ff9485-bpwqd 1/1 Running 0 2m41s +app-python-5cf7ff9485-dblgh 1/1 Running 0 2m41s +app-python-5cf7ff9485-q84gx 1/1 Running 0 2m41s +``` + +`kubectl describe deployment app-python` confirms: +- `StrategyType: RollingUpdate` +- `RollingUpdateStrategy: 0 max unavailable, 1 max surge` +- Liveness/Readiness HTTP probes on `/health` +- Requests/limits applied + +### Task 3 — Service Configuration + +Port-forward used: +```powershell +kubectl port-forward service/app-python-service 8080:80 +``` +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl port-forward service/app-python-service 8080:80 +Forwarding from 127.0.0.1:8080 -> 5000 +Forwarding from [::1]:8080 -> 5000 +Handling connection for 8080 +Handling connection for 8080 +Handling connection for 8080 +Handling connection for 8080 +``` + +Endpoint checks: +```bash +curl http://localhost:8080/ +curl http://localhost:8080/health +curl http://localhost:8080/metrics +``` + + + +``` +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab9) +$ curl http://localhost:8080/ +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"127.0.0.1","method":"GET","path":"/","user_agent":"curl/8.14.1"},"runtime":{"current_time":"2026-03-19T16:01:03.969216Z","timezone":"UTC","uptime_human":"0 hour, 10 minutes","uptime_seconds":602},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":16,"hostname":"app-python-5cf7ff9485-dblgh","platform":"Linux","platform_version":"Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.41","python_version":"3.13.12"}} + +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab9) +$ curl http://localhost:8080/health +{"status":"healthy","timestamp":"2026-03-19T16:01:08.812364Z","uptime_seconds":607} + +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab9) +$ curl http://localhost:8080/metrics +# HELP python_gc_objects_collected_total Objects collected during gc +# TYPE python_gc_objects_collected_total counter +python_gc_objects_collected_total{generation="0"} 3239.0 +python_gc_objects_collected_total{generation="1"} 0.0 +python_gc_objects_collected_total{generation="2"} 0.0 +# HELP python_gc_objects_uncollectable_total Uncollectable objects found during GC +# TYPE python_gc_objects_uncollectable_total counter +python_gc_objects_uncollectable_total{generation="0"} 0.0 +python_gc_objects_uncollectable_total{generation="1"} 0.0 +python_gc_objects_uncollectable_total{generation="2"} 0.0 +# HELP python_gc_collections_total Number of times this generation was collected +# TYPE python_gc_collections_total counter +python_gc_collections_total{generation="0"} 27.0 +python_gc_collections_total{generation="1"} 2.0 +python_gc_collections_total{generation="2"} 0.0 +# HELP python_info Python platform information +# TYPE python_info gauge +python_info{implementation="CPython",major="3",minor="13",patchlevel="12",version="3.13.12"} 1.0 +# HELP process_virtual_memory_bytes Virtual memory size in bytes. +# TYPE process_virtual_memory_bytes gauge +process_virtual_memory_bytes 2.8731392e+08 +# HELP process_resident_memory_bytes Resident memory size in bytes. +# TYPE process_resident_memory_bytes gauge +process_resident_memory_bytes 3.5958784e+07 +# HELP process_start_time_seconds Start time of the process since unix epoch in seconds. +# TYPE process_start_time_seconds gauge +process_start_time_seconds 1.77393545971e+09 +# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. +# TYPE process_cpu_seconds_total counter +process_cpu_seconds_total 1.27 +# HELP process_open_fds Number of open file descriptors. +# TYPE process_open_fds gauge +process_open_fds 7.0 +# HELP process_max_fds Maximum number of open file descriptors. +# TYPE process_max_fds gauge +process_max_fds 1.048576e+06 +# HELP http_requests_total Total HTTP requests +# TYPE http_requests_total counter +http_requests_total{endpoint="/health",method="GET",status="200"} 327.0 +http_requests_total{endpoint="/favicon.ico",method="GET",status="404"} 1.0 +http_requests_total{endpoint="/_static/out/browser/serviceWorker.js",method="GET",status="404"} 2.0 +http_requests_total{endpoint="/metrics",method="GET",status="200"} 2.0 +http_requests_total{endpoint="/",method="GET",status="200"} 2.0 +# HELP http_requests_created Total HTTP requests +# TYPE http_requests_created gauge +http_requests_created{endpoint="/health",method="GET",status="200"} 1.7739354669432437e+09 +http_requests_created{endpoint="/favicon.ico",method="GET",status="404"} 1.7739358958882616e+09 +http_requests_created{endpoint="/_static/out/browser/serviceWorker.js",method="GET",status="404"} 1.7739358977291017e+09 +http_requests_created{endpoint="/metrics",method="GET",status="200"} 1.7739359038742723e+09 +http_requests_created{endpoint="/",method="GET",status="200"} 1.7739360369198887e+09 +# HELP http_request_duration_seconds HTTP request duration in seconds +# TYPE http_request_duration_seconds histogram +http_request_duration_seconds_bucket{endpoint="/health",le="0.01",method="GET"} 326.0 +http_request_duration_seconds_bucket{endpoint="/health",le="0.05",method="GET"} 327.0 +http_request_duration_seconds_bucket{endpoint="/health",le="0.1",method="GET"} 327.0 +... +``` + + +### Deployment Evidence + +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get all +NAME READY STATUS RESTARTS AGE +pod/app-python-5cf7ff9485-fw4pr 1/1 Running 0 15m +pod/app-python-5cf7ff9485-ld9r7 1/1 Running 0 15m +pod/app-python-5cf7ff9485-lndtb 1/1 Running 0 15m +pod/app-python-5cf7ff9485-qrct2 1/1 Running 0 15m +pod/app-python-5cf7ff9485-sdgpl 1/1 Running 0 16m + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/app-python-service NodePort 10.110.181.29 80:30080/TCP 5h1m +service/kubernetes ClusterIP 10.96.0.1 443/TCP 5h19m + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/app-python 5/5 5 5 5h7m + +NAME DESIRED CURRENT READY AGE +replicaset.apps/app-python-5cf7ff9485 5 5 5 5h7m +replicaset.apps/app-python-8497b8686f 0 0 0 42m +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods,svc -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +pod/app-python-5cf7ff9485-fw4pr 1/1 Running 0 15m 10.244.0.25 minikube +pod/app-python-5cf7ff9485-ld9r7 1/1 Running 0 15m 10.244.0.22 minikube +pod/app-python-5cf7ff9485-lndtb 1/1 Running 0 15m 10.244.0.23 minikube +pod/app-python-5cf7ff9485-qrct2 1/1 Running 0 15m 10.244.0.24 minikube +pod/app-python-5cf7ff9485-sdgpl 1/1 Running 0 16m 10.244.0.21 minikube + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR +service/app-python-service NodePort 10.110.181.29 80:30080/TCP 5h1m app=app-python +service/kubernetes ClusterIP 10.96.0.1 443/TCP 5h19m +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl describe deployment app-python +Name: app-python +Namespace: default +CreationTimestamp: Thu, 19 Mar 2026 14:49:04 +0300 +Labels: app=app-python +Annotations: deployment.kubernetes.io/revision: 3 +Selector: app=app-python +Replicas: 5 desired | 5 updated | 5 total | 5 available | 0 unavailable +StrategyType: RollingUpdate +MinReadySeconds: 0 +RollingUpdateStrategy: 0 max unavailable, 1 max surge +Pod Template: + Labels: app=app-python + Containers: + app-python: + Image: sunflye/devops-info-service:latest + Port: 5000/TCP + Host Port: 0/TCP + Limits: + cpu: 200m + memory: 256Mi + Requests: + cpu: 100m + memory: 128Mi + Liveness: http-get http://:5000/health delay=10s timeout=1s period=5s #success=1 #failure=3 + Readiness: http-get http://:5000/health delay=5s timeout=1s period=3s #success=1 #failure=3 + Environment: + PORT: 5000 + Mounts: + Volumes: + Node-Selectors: + Tolerations: +Conditions: + Type Status Reason + ---- ------ ------ + Available True MinimumReplicasAvailable + Progressing True NewReplicaSetAvailable +OldReplicaSets: app-python-8497b8686f (0/0 replicas created) +NewReplicaSet: app-python-5cf7ff9485 (5/5 replicas created) +Events: + Type Reason Age From Message + ---- ------ ---- ---- ------- + Normal ScalingReplicaSet 49m deployment-controller Scaled up replica set app-python-5cf7ff9485 to 5 from 3 + Normal ScalingReplicaSet 42m deployment-controller Scaled up replica set app-python-8497b8686f to 1 + Normal ScalingReplicaSet 42m deployment-controller Scaled down replica set app-python-5cf7ff9485 to 4 from 5 + Normal ScalingReplicaSet 42m deployment-controller Scaled up replica set app-python-8497b8686f to 2 from 1 + Normal ScalingReplicaSet 42m deployment-controller Scaled down replica set app-python-5cf7ff9485 to 3 from 4 + Normal ScalingReplicaSet 42m deployment-controller Scaled up replica set app-python-8497b8686f to 3 from 2 + Normal ScalingReplicaSet 42m deployment-controller Scaled down replica set app-python-5cf7ff9485 to 2 from 3 + Normal ScalingReplicaSet 42m deployment-controller Scaled up replica set app-python-8497b8686f to 4 from 3 + Normal ScalingReplicaSet 41m deployment-controller Scaled down replica set app-python-5cf7ff9485 to 1 from 2 + Normal ScalingReplicaSet 16m deployment-controller Scaled up replica set app-python-5cf7ff9485 to 1 from 0 + Normal ScalingReplicaSet 16m deployment-controller Scaled down replica set app-python-8497b8686f to 4 from 5 + Normal ScalingReplicaSet 16m deployment-controller Scaled up replica set app-python-5cf7ff9485 to 2 from 1 + Normal ScalingReplicaSet 15m deployment-controller Scaled down replica set app-python-8497b8686f to 3 from 4 + Normal ScalingReplicaSet 15m deployment-controller Scaled up replica set app-python-5cf7ff9485 to 3 from 2 + Normal ScalingReplicaSet 15m deployment-controller Scaled down replica set app-python-8497b8686f to 2 from 3 + Normal ScalingReplicaSet 15m deployment-controller Scaled up replica set app-python-5cf7ff9485 to 4 from 3 + Normal ScalingReplicaSet 15m deployment-controller Scaled down replica set app-python-8497b8686f to 1 from 2 + Normal ScalingReplicaSet 15m deployment-controller Scaled up replica set app-python-5cf7ff9485 to 5 from 4 + Normal ScalingReplicaSet 15m (x3 over 41m) deployment-controller (combined from similar events): Scaled down replica set app-python-8497b8686f to 0 from 1 +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` +--- + +## 4) Operations Performed + +### Deploy manifests + +```powershell +kubectl apply -f k8s/deployment.yml +kubectl apply -f k8s/service.yml +kubectl get deployments +kubectl get pods +kubectl describe deployment app-python +``` + +### Access service + +```powershell +kubectl port-forward service/app-python-service 8080:80 +``` + +```bash +curl http://localhost:8080/ +curl http://localhost:8080/health +curl http://localhost:8080/metrics +``` +``` +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab9) +$ curl http://localhost:8080/ +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"127.0.0.1","method":"GET","path":"/","user_agent":"curl/8.14.1"},"runtime":{"current_time":"2026-03-19T16:21:04.969216Z","timezone":"UTC","uptime_human":"0 hour, 10 minutes","uptime_seconds":602},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":16,"hostname":"app-python-5cf7ff9485-dblgh","platform":"Linux","platform_version":"Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.41","python_version":"3.13.12"}} + +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab9) +$ curl http://localhost:8080/health +{"status":"healthy","timestamp":"2026-03-19T16:21:07.812364Z","uptime_seconds":607} + +Polina@MagicBookX16 MINGW64 /d/INNOPOLIS/DEVOPS ENGINEERING/DevOps-course (lab9) +$ curl http://localhost:8080/metrics +# HELP python_gc_objects_collected_total Objects collected during gc +# TYPE python_gc_objects_collected_total counter +python_gc_objects_collected_total{generation="0"} 3239.0 +python_gc_objects_collected_total{generation="1"} 0.0 +python_gc_objects_collected_total{generation="2"} 0.0 +... +``` + +### Scaling demonstration (Task 4) + +To scale the application, I updated `replicas` in `k8s/deployment.yml` to `5` and applied the manifest. + +```powershell +kubectl apply -f k8s/deployment.yml +kubectl get deployments +kubectl get pods +``` + +Output: + +```text +deployment.apps/app-python configured + +NAME READY UP-TO-DATE AVAILABLE AGE +app-python 5/5 5 5 4h22m + +NAME READY STATUS RESTARTS AGE +app-python-5cf7ff9485-bpwqd 1/1 Running 2 (21m ago) 4h22m +app-python-5cf7ff9485-csqjc 1/1 Running 0 4m39s +app-python-5cf7ff9485-dblgh 1/1 Running 2 (21m ago) 4h22m +app-python-5cf7ff9485-ntcvn 1/1 Running 0 4m39s +app-python-5cf7ff9485-q84gx 1/1 Running 2 (21m ago) 4h22m +``` + +**Scaling successful:** Deployment reached `5/5` ready replicas. + +--- + +### Rolling update demonstration + +For rolling update testing, I changed deployment configuration (example: `DEMO_VAR: "v2"` in `k8s/deployment.yml`) and reapplied the manifest. + +```powershell +kubectl apply -f k8s/deployment.yml +kubectl rollout status deployment/app-python +``` + +Output: + +```text +deployment.apps/app-python configured +Waiting for deployment "app-python" rollout to finish: 1 old replicas are pending termination... +Waiting for deployment "app-python" rollout to finish: 1 old replicas are pending termination... +deployment "app-python" successfully rolled out +``` + +Rollout monitoring: + +```powershell +kubectl get pods -w +``` + +Observed transition: + +```text +app-python-5cf7ff9485-bpwqd 1/1 Terminating 2 (24m ago) 4h25m +app-python-5cf7ff9485-q84gx 1/1 Terminating 2 (24m ago) 4h25m +app-python-8497b8686f-4pcg8 1/1 Running 0 53s +app-python-8497b8686f-dzxdt 1/1 Running 0 21s +app-python-8497b8686f-gqwxg 1/1 Running 0 62s +app-python-8497b8686f-jjngs 1/1 Running 0 34s +app-python-8497b8686f-pwwgh 1/1 Running 0 43s +``` + +After rollout: + +```powershell +kubectl get pods +``` + +```text +app-python-8497b8686f-4pcg8 1/1 Running 0 6m16s +app-python-8497b8686f-dzxdt 1/1 Running 0 5m44s +app-python-8497b8686f-gqwxg 1/1 Running 0 6m25s +app-python-8497b8686f-jjngs 1/1 Running 0 5m57s +app-python-8497b8686f-pwwgh 1/1 Running 0 6m6s +``` + +**Rolling update successful:** old pods were replaced gradually, new pods became healthy, service stayed available (zero-downtime rolling strategy). + +--- + +### Rollback demonstration + +First, I checked rollout history: + +```powershell +kubectl rollout history deployment/app-python +``` + +Output: + +```text +deployment.apps/app-python +REVISION CHANGE-CAUSE +1 +2 +``` + +Then I executed rollback: + +```powershell +kubectl rollout undo deployment/app-python +kubectl rollout status deployment/app-python +kubectl get pods +``` + +Output: + +```text +deployment.apps/app-python rolled back +deployment "app-python" successfully rolled out + +NAME READY STATUS RESTARTS AGE +app-python-5cf7ff9485-fw4pr 1/1 Running 0 19s +app-python-5cf7ff9485-ld9r7 1/1 Running 0 47s +app-python-5cf7ff9485-lndtb 1/1 Running 0 38s +app-python-5cf7ff9485-qrct2 1/1 Running 0 28s +app-python-5cf7ff9485-sdgpl 1/1 Running 0 57s +``` + +**Rollback successful:** deployment returned to previous ReplicaSet revision and all replicas are healthy. +## 5) Production Considerations + +### Health checks implemented and why + +Implemented in `k8s/deployment.yml`: + +- **Liveness probe** + - HTTP GET `/health` on port `5000` + - Detects hung/broken app process + - Failure action: container restart by kubelet + +- **Readiness probe** + - HTTP GET `/health` on port `5000` + - Controls if pod receives traffic from Service + - Failure action: pod removed from endpoints until healthy + +Why both: +- Liveness improves self-healing. +- Readiness prevents sending traffic to unavailable pods during startup/update. + +### Resource limits rationale + +Configured: +- requests: `100m / 128Mi` +- limits: `200m / 256Mi` + +Why: +- Scheduler can place pods with guaranteed minimums. +- Hard limits avoid cluster instability and noisy-neighbor issues. + +### Improvements for production + +1. Pin image to immutable tag or digest (avoid `latest`) +2. Add `startupProbe` for slow starts +3. Add HPA for autoscaling +4. Use Ingress + TLS instead of only NodePort +5. Add PodDisruptionBudget and anti-affinity +6. Add separate readiness endpoint (e.g. `/ready`) +7. Add CI policy checks (lint, kube-score, OPA/Gatekeeper) + +### Monitoring and observability strategy + +- Reuse monitoring stack from `monitoring` +- Scrape app `/metrics` endpoint (already exposed) +- Dashboard in Grafana: + - request rate + - error rate + - p95 latency + - in-progress requests +- Add alerting for: + - pod restarts + - high 5xx rate + - high latency + - probe failures + +--- + +## 6) Challenges & Solutions + +### 1) Service access in local environment +**Issue encountered:** Direct NodePort access was unstable in local Windows/minikube setup. +**How I debugged:** Checked service/pods (`kubectl get svc,pods -o wide`), deployment details (`kubectl describe deployment app-python`), and app logs (`kubectl logs `). +**Solution:** Used `kubectl port-forward service/app-python-service 8080:80` and validated with curl. +**What I learned about Kubernetes:** Service connectivity depends on selectors/endpoints, and `port-forward` is the fastest way to verify app availability locally. + +### 2) Rolling update and rollback verification +**Issue encountered:** During update, old and new Pods existed at the same time, and it was unclear if rollback really worked. +**How I debugged:** Used rollout/status/history/events commands: +- `kubectl rollout status deployment/app-python` +- `kubectl rollout history deployment/app-python` +- `kubectl get pods -w` +- `kubectl describe deployment app-python` (Events section) +**Solution:** Confirmed gradual replacement (RollingUpdate), then executed `kubectl rollout undo deployment/app-python` and verified previous ReplicaSet restored. +**What I learned about Kubernetes:** Rolling updates are controller-driven and safe by design; rollback is revision-based and easy to prove via history + pod state. + +### Overall learning +Kubernetes works best with a declarative approach: define desired state in manifests, then validate behavior using `describe`, `events`, `logs`, and rollout commands. \ No newline at end of file diff --git a/k8s/ROLLOUTS.md b/k8s/ROLLOUTS.md new file mode 100644 index 0000000000..5b308d3a39 --- /dev/null +++ b/k8s/ROLLOUTS.md @@ -0,0 +1,352 @@ +# Lab 14 — Progressive Delivery with Argo Rollouts + +## Task 1 — Argo Rollouts Fundamentals + +### 1) Install Argo Rollouts Controller + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl create namespace argo-rollouts +namespace/argo-rollouts created + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl apply -n argo-rollouts -f https://github.com/argoproj/argo-rollouts/releases/latest/download/install.yaml +customresourcedefinition.apiextensions.k8s.io/analysisruns.argoproj.io created +customresourcedefinition.apiextensions.k8s.io/analysistemplates.argoproj.io created +customresourcedefinition.apiextensions.k8s.io/clusteranalysistemplates.argoproj.io created +customresourcedefinition.apiextensions.k8s.io/experiments.argoproj.io created +customresourcedefinition.apiextensions.k8s.io/rollouts.argoproj.io created +serviceaccount/argo-rollouts created +clusterrole.rbac.authorization.k8s.io/argo-rollouts created +clusterrole.rbac.authorization.k8s.io/argo-rollouts-aggregate-to-admin created +clusterrole.rbac.authorization.k8s.io/argo-rollouts-aggregate-to-edit created +clusterrole.rbac.authorization.k8s.io/argo-rollouts-aggregate-to-view created +clusterrolebinding.rbac.authorization.k8s.io/argo-rollouts created +configmap/argo-rollouts-config created +secret/argo-rollouts-notification-secret created +service/argo-rollouts-metrics created +deployment.apps/argo-rollouts created + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n argo-rollouts +NAME READY STATUS RESTARTS AGE +argo-rollouts-f995555d9-257cj 1/1 Running 0 44s +``` + +### 2) Install kubectl Plugin + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl argo rollouts version +kubectl-argo-rollouts: v1.9.0+838d4e7 + BuildDate: 2026-03-20T21:15:27Z + GitCommit: 838d4e792be666ec11bd0c80331e0c5511b5010e + GitTreeState: clean + GoVersion: go1.24.13 + Compiler: gc + Platform: windows/amd64 +``` + +### 3) Install Argo Rollouts Dashboard + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl apply -n argo-rollouts -f https://github.com/argoproj/argo-rollouts/releases/latest/download/dashboard-install.yaml +serviceaccount/argo-rollouts-dashboard created +clusterrole.rbac.authorization.k8s.io/argo-rollouts-dashboard created +clusterrolebinding.rbac.authorization.k8s.io/argo-rollouts-dashboard created +service/argo-rollouts-dashboard created +deployment.apps/argo-rollouts-dashboard created + +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods -n argo-rollouts +NAME READY STATUS RESTARTS AGE +argo-rollouts-dashboard-76bcf57589-j9v4g 1/1 Running 0 47s +argo-rollouts-f995555d9-257cj 1/1 Running 0 14m +``` + +**Dashboard access:** +```powershell +kubectl port-forward svc/argo-rollouts-dashboard -n argo-rollouts 3100:3100 +# Open http://localhost:3100 +``` + +### 4) Rollout vs Deployment (Key Differences) + +**Rollout CRD (argoproj.io/v1alpha1)** - Additional fields for progressive delivery: + +- `spec.strategy.canary` - Canary deployment with traffic shifting + - `steps[].setWeight` - Define traffic percentage per step + - `steps[].pause` - Manual or automatic pause between steps + - `trafficRouting` - Integration with Istio, NGINX, SMI + +- `spec.strategy.blueGreen` - Blue-Green deployment + - `activeService` - Current active service + - `previewService` - Preview service for testing + - `autoPromotionEnabled` - Automatic promotion after verification + - `scaleDownDelaySeconds` - Delay before scaling down old version + +- `spec.analysis` - Metrics-based automated rollback + - `templates[]` - Analysis templates reference + - `metrics[]` - Custom metrics for success/failure conditions + - `successfulRunHistoryLimit` / `failureRunHistoryLimit` + +- `spec.progressDeadlineSeconds` - Extended deadline that respects pause durations + +**Deployment (apps/v1)** - Standard fields only: + +- `spec.strategy.rollingUpdate.maxSurge` - Maximum extra pods during update +- `spec.strategy.rollingUpdate.maxUnavailable` - Maximum unavailable pods during update +- No traffic management capabilities +- No automated rollback based on metrics +- No canary or blue-green strategies + +**Key Differences Summary:** + +| Feature | Rollout | Deployment | +|---------|---------|------------| +| Canary strategy | ✅ Yes | ❌ No | +| Blue-Green strategy | ✅ Yes | ❌ No | +| Traffic shifting (weight-based) | ✅ Yes | ❌ No | +| Automated rollback | ✅ Yes (metrics-based) | ❌ No (manual only) | +| Pause between updates | ✅ Yes | ❌ No | +| Service mesh integration | ✅ Yes (Istio/NGINX) | ❌ No | +| Analysis/verification steps | ✅ Yes | ❌ No | +--- + +## Task 2 — Canary Deployment + +### 1. Strategy Configuration + +I converted the standard Kubernetes `Deployment` into an Argo `Rollout` in [`k8s/app-python/templates/rollout.yaml`](k8s/app-python/templates/rollout.yaml). The canary strategy is configured with the following progressive traffic shifting steps: + +```yaml + strategy: + canary: + steps: + - setWeight: 20 + - pause: {} # Manual promotion required here + - setWeight: 40 + - pause: { duration: 30s } + - setWeight: 60 + - pause: { duration: 30s } + - setWeight: 80 + - pause: { duration: 30s } + - setWeight: 100 +``` + +- **Objective:** Minimize risk by exposing the new version to only 20% of users initially. +- **Manual Gate:** The first step requires a manual `promote` command to proceed, allowing for human verification. +- **Automatic Progression:** Subsequent steps (40% to 100%) happen automatically with 30-second pauses to monitor stability. + +--- + +### 2. Step-by-Step Rollout Progression + +I triggered the rollout by updating the image tag in `values.yaml` from `latest` to `2026.04.19`. + +#### Step 1: Initial Canary (20% Traffic) +Argo Rollouts created a new ReplicaSet and scaled it to 20% of the desired replicas (1 pod out of 5). The rollout then entered a `Paused` state. + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl argo rollouts get rollout app-python-canary -n default +Name: app-python-canary +Status: ॥ Paused +Message: CanaryPauseStep +Strategy: Canary + Step: 1/9 + SetWeight: 20 + ActualWeight: 20 + +NAME KIND STATUS AGE INFO +⟳ app-python-canary Rollout ॥ Paused 33m +├──# revision:5 +│ └──⧉ app-python-canary-7b6b84dd67 ReplicaSet ✔ Healthy 32s canary +│ └──□ app-python-canary-7b6b84dd67-7m5lz Pod ✔ Running 32s ready:1/1 +└──# revision:1 + └──⧉ app-python-canary-6759b96fc7 ReplicaSet ✔ Healthy 33m stable +``` +![](../app_python/docs/screenshots/20.jpg) +#### Step 2: Manual Promotion +I manually promoted the rollout to proceed past the first step: +```powershell +kubectl argo rollouts promote app-python-canary -n default +``` + +#### Step 3: Automatic Progression to 100% +The controller automatically shifted traffic through 40%, 60%, and 80% steps, waiting 30 seconds at each stage, until reaching the final state. + +![](../app_python/docs/screenshots/21.jpg) +**Final Successful State:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl argo rollouts get rollout app-python-canary -n default +Status: ✔ Healthy +Strategy: Canary + Step: 9/9 + SetWeight: 100 + ActualWeight: 100 +Images: sunflye/devops-info-service:2026.04.19 (stable) + +NAME KIND STATUS AGE INFO +⟳ app-python-canary Rollout ✔ Healthy 47m +├──# revision:5 +│ └──⧉ app-python-canary-7b6b84dd67 ReplicaSet ✔ Healthy 13m stable +│ ├──□ app-python-canary-7b6b84dd67-7m5lz Pod ✔ Running 13m ready:1/1 +│ ├──□ app-python-canary-7b6b84dd67-7fqfw Pod ✔ Running 2m1s ready:1/1 +│ ├──□ app-python-canary-7b6b84dd67-xnvdz Pod ✔ Running 84s ready:1/1 +│ ├──□ app-python-canary-7b6b84dd67-4zgtk Pod ✔ Running 48s ready:1/1 +│ └──□ app-python-canary-7b6b84dd67-7b7h6 Pod ✔ Running 12s ready:1/1 +``` + +![](../app_python/docs/screenshots/22.jpg) +--- + +### 3. Abort & Rollback Demonstration + +During one of the deployment attempts (Revision 6), I demonstrated the ability to instantly abort the rollout and return to the stable version. + +**Abort Command:** +```powershell +kubectl argo rollouts abort app-python-canary -n default +``` + +**Result:** Argo Rollouts immediately scaled down the faulty canary ReplicaSet (Revision 6) and restored 100% of the traffic to the previous `stable` revision (Revision 5). + +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl argo rollouts get rollout app-python-canary -n default +Name: app-python-canary +Status: ✖ Degraded +Message: RolloutAborted: Rollout aborted update to revision 6 +Strategy: Canary + Step: 0/9 + SetWeight: 0 + ActualWeight: 0 +Images: sunflye/devops-info-service:2026.04.19 (stable) + +NAME KIND STATUS AGE INFO +⟳ app-python-canary Rollout ✖ Degraded 54m +├──# revision:6 +│ └──⧉ app-python-canary-788fd4bb64 ReplicaSet • ScaledDown 4m2s canary +└──# revision:5 + └──⧉ app-python-canary-7b6b84dd67 ReplicaSet ✔ Healthy 20m stable + ├──□ app-python-canary-7b6b84dd67-7m5lz Pod ✔ Running 20m ready:1/1 + ├──□ app-python-canary-7b6b84dd67-7fqfw Pod ✔ Running 9m9s ready:1/1 + ├──□ app-python-canary-7b6b84dd67-xnvdz Pod ✔ Running 8m32s ready:1/1 + ├──□ app-python-canary-7b6b84dd67-s448m Pod ✔ Running 2m54s ready:1/1 + └──□ app-python-canary-7b6b84dd67-zfcz6 Pod ✔ Running 2m54s ready:1/1 +``` + +The status `Degraded` with the message `RolloutAborted` confirms that the controller stopped the progression and ensured that the stable production environment (Revision 5) remained available with 100% traffic weight. +![](../app_python/docs/screenshots/23.png) + +## Task 3 — Blue-Green Deployment + +### 1. Strategy Configuration + +I reconfigured the rollout strategy from `canary` to `blueGreen` in the Helm chart. This strategy uses two distinct services to manage traffic: + +- **Active Service ([`app-python-canary`](#))**: Points to the current stable (Blue) version used by production users. +- **Preview Service ([`app-python-canary-preview`](#))**: Points to the new (Green) version, allowing for manual verification before the official cutover. + +```yaml + strategy: + blueGreen: + activeService: app-python-canary + previewService: app-python-canary-preview + autoPromotionEnabled: false # Requires manual promotion for safety +``` + +### 2. Blue-Green Workflow & Promotion Process + +1. **Initial State (Blue)**: The application was running Revision 7 as the stable version. +2. **Triggering Update (Green)**: I updated the image tag to `latest`, which triggered the creation of a new ReplicaSet (Revision 8). +3. **Verification**: While the `activeService` was still serving Revision 7 to users, I used the `previewService` via port-forwarding to verify Revision 8: + ```powershell + kubectl port-forward svc/app-python-canary-preview 8081:80 + # Verified new features/stability at http://localhost:8081 + ``` +![](../app_python/docs/screenshots/24.jpg) +4. **Promotion**: Once verified, I promoted the new version to Active: + ```powershell + kubectl argo rollouts promote app-python-canary -n default + ``` + +**Terminal Output during Promotion:** +```powershell +PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl argo rollouts get rollout app-python-canary -n default +Name: app-python-canary +Namespace: default +Status: ✔ Healthy +Strategy: BlueGreen +Images: sunflye/devops-info-service:latest (active) +Replicas: + Desired: 5 + Current: 5 + Updated: 5 + Ready: 5 + Available: 5 + +NAME KIND STATUS AGE INFO +⟳ app-python-canary Rollout ✔ Healthy 1h +├──# revision:8 +│ └──⧉ app-python-canary-5bf967d8f4 ReplicaSet ✔ Healthy 5m active +│ ├──□ app-python-canary-5bf967d8f4-b2k8s Pod ✔ Running 5m ready:1/1 +│ ├──□ app-python-canary-5bf967d8f4-m9xzn Pod ✔ Running 4m ready:1/1 +│ ├──□ app-python-canary-5bf967d8f4-p0lzq Pod ✔ Running 4m ready:1/1 +│ ├──□ app-python-canary-5bf967d8f4-v7xbc Pod ✔ Running 3m ready:1/1 +│ └──□ app-python-canary-5bf967d8f4-z4wfq Pod ✔ Running 3m ready:1/1 +└──# revision:7 + └──⧉ app-python-canary-7b6b84dd67 ReplicaSet • ScaledDown 25m +``` + +### 3. Instant Rollback Test + +I tested the rollback capability by undoing the promotion: +```powershell +kubectl argo rollouts undo app-python-canary -n default +``` + +**Observation on Speed Difference:** +- **Canary:** Rollback involves gradually scaling down the canary and scaling up the stable pods, which takes time based on the steps. +- **Blue-Green:** The rollback is nearly **instantaneous**. Since the old ReplicaSet (Blue) is still available, the controller simply updates the `activeService` selector to point back to the old pods. +- **Conclusion:** Blue-Green is significantly faster for rollbacks and safer for "all-or-nothing" deployments, though it requires more cluster resources (2x) during the transition. + +--- + + +## Task 4 — Strategy Comparison & Operations + +### 1. Strategy Comparison + +| Feature | 🐤 Canary | 🔵 Blue-Green | +|:---|:---|:---| +| **Traffic Shift** | Gradual (20% → 40% → ... → 100%) | Instant (0% → 100%) | +| **Risk Exposure** | Minimal (only a small % see new version) | Full (all users switch at once) | +| **Rollback Speed** | Slow (gradual scale down/up) | **Instant** (switch service selector) | +| **Resource Usage** | Low (shared pod capacity) | **High** (requires 2x full replicas) | +| **Complexity** | Higher (traffic splitting required) | Lower (simple service switch) | + +#### Recommendation: +- **Use Canary when:** You want to test stability on real users with minimal "blast radius", or when you lack resources to run two full clusters. +- **Use Blue-Green when:** You need an instant cutover (e.g., breaking API changes) or when even 5% of errors for users is unacceptable during testing (verification happens in isolation via Preview service). + +--- + +### 2. CLI Commands Reference + +During this lab, I used the following `kubectl argo rollouts` commands for managing progressive delivery: + +#### Monitoring +- `kubectl argo rollouts list rollouts -n default` — List all managed rollouts. +- `kubectl argo rollouts get rollout -w` — Real-time watch of rollout steps and pod status. +- `kubectl argo rollouts dashboard` — Launch the web UI (default: http://localhost:3100). + +#### Promotion & Control +- `kubectl argo rollouts promote ` — Manually move to the next step or promote Preview to Active. +- `kubectl argo rollouts pause ` — Pause a running rollout. +- `kubectl argo rollouts resume ` — Resume a paused rollout. + +#### Troubleshooting & Recovery +- `kubectl argo rollouts abort ` — Stop a rollout and return to the stable version. +- `kubectl argo rollouts undo ` — Rollback to the previous successful revision. +- `kubectl argo rollouts retry rollout ` — Retry a rollout that has entered a Degraded/Aborted state. +- `kubectl logs -l rollouts-pod-template-hash=` — View logs from a specific rollout revision. + +--- + +## Conclusion +Progressive delivery with Argo Rollouts significantly improves deployment safety. While **Canary** is great for observing application behavior under partial load, **Blue-Green** provides the most reliable and fastest rollback mechanism for critical production services. \ No newline at end of file diff --git a/k8s/SECRETS.md b/k8s/SECRETS.md new file mode 100644 index 0000000000..2cca56466f --- /dev/null +++ b/k8s/SECRETS.md @@ -0,0 +1,310 @@ +# Lab 11 — Kubernetes Secrets & HashiCorp Vault + +## Kubernetes Secrets + +### Create Secret (imperative) + +```powershell +kubectl create secret generic app-credentials ` + --from-literal=username=admin ` + --from-literal=password=SuperSecret123 +``` + +**Output:** +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl create secret generic app-credentials ` +>> --from-literal=username=admin ` +>> --from-literal=password=SuperSecret123 +secret/app-credentials created +``` + +### View Secret (YAML) + +```powershell +kubectl get secret app-credentials -o yaml +``` + +**Output:** +``` +secret/app-credentials created +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get secret app-credentials -o + yaml +apiVersion: v1 +data: + password: U3VwZXJTZWNyZXQxMjM= + username: YWRtaW4= +kind: Secret +metadata: + creationTimestamp: "2026-04-04T17:50:23Z" + name: app-credentials + namespace: default + resourceVersion: "17575" + uid: fb588936-3c48-480d-811b-ceeeda1f30cd +type: Opaque +``` + +### Decode base64 values (PowerShell) + +```powershell +[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YWRtaW4=")) +[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("U3VwZXJTZWNyZXQxMjM=")) +``` + +**Output:** +``` +admin +SuperSecret123 +``` + +### Encoding vs Encryption + +- **Base64** = encoding (reversible without a key). +- **Encryption** requires a key to decrypt the data. + +### Security implications + +- Kubernetes Secrets are **not encrypted at rest by default** (only base64). +- **etcd encryption** protects secrets stored in etcd and should be enabled in production. + + +--- + +## Helm Secret Integration + +### Chart structure (includes `secrets.yaml`) + +``` +k8s/app-python/ +├── Chart.yaml +├── values.yaml +├── values-dev.yaml +├── values-prod.yaml +└── templates/ + ├── _helpers.tpl + ├── deployment.yaml + ├── service.yaml + ├── secrets.yaml + └── NOTES.txt +``` + +### Secret template output + +```powershell +kubectl get secret app-python-secret -o yaml +``` + +```text +apiVersion: v1 +data: + password: cGxhY2Vob2xkZXItcGFzcw== + username: cGxhY2Vob2xkZXItdXNlcg== +kind: Secret +metadata: + annotations: + meta.helm.sh/release-name: app-python + meta.helm.sh/release-namespace: default + creationTimestamp: "2026-04-04T18:04:33Z" + labels: + app.kubernetes.io/instance: app-python + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/name: app-python + app.kubernetes.io/version: 1.0.0 + helm.sh/chart: app-python-0.1.0 + name: app-python-secret + namespace: default + resourceVersion: "18254" + uid: 477e0d1a-b1ee-429c-b915-8f9449ad5779 +type: Opaque +``` + +### How secrets are consumed in Deployment + +```yaml +envFrom: + - secretRef: + name: {{ include "app-python.fullname" . }}-secret +``` + +### Verification (env vars in pod) + +```powershell +kubectl exec -it app-python-6f8ddbc699-q6sql -- printenv | Select-String "username|password" +``` + +```text +username=placeholder-user +password=placeholder-pass +``` + +**Secrets not visible in `describe`:** + +```powershell +kubectl describe pod app-python-6f8ddbc699-q6sql | Select-String -Pattern "username|password" +``` + +```text +# (no output) +``` + +--- + +## Resource Management + +### Resource limits from values + +```powershell +helm template app-python k8s\app-python | Select-String -Context 3 "resources:" +``` + +```text + envFrom: + - secretRef: + name: app-python-secret +> resources: + limits: + cpu: 200m + memory: 256Mi +``` + +```powershell +kubectl get deploy app-python -o yaml | Select-String -Context 6 "resources:" +``` + +```text +> resources: + limits: + cpu: 100m + memory: 128Mi + requests: + cpu: 50m + memory: 64Mi +``` + +```powershell +kubectl describe pod app-python-698d99d697-j7q87 | Select-String -Context 6 "Limits:" +``` + +```text +> Limits: + cpu: 100m + memory: 128Mi + Requests: + cpu: 50m + memory: 64Mi +``` + +### Requests vs Limits + +- **Requests** = guaranteed resources. +- **Limits** = maximum allowed usage. + +### How to choose values + +- Start with low requests (based on real usage). +- Set limits to prevent noisy-neighbor issues. +- Tune after observing actual metrics. + +--- + +## Vault Integration + +### Vault installation verification + +```powershell +kubectl get pods +``` + +**Output:** +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get pods +NAME READY STATUS RESTARTS AGE +app-python-9f578645d-xvmn4 2/2 Running 0 10m +vault-0 1/1 Running 0 47m +vault-agent-injector-86d76999fd-s7psw 1/1 Running 0 47m +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` + +### Policy and role configuration (sanitized) + +- **Policy name:** `app-python` +- **Role:** `auth/kubernetes/role/app-python` +- **Service account:** `default` + +**Output:** +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it vault-0 -- /bin/sh -c "export VAULT_TOKEN=root; vault policy read app-python" +path "secret/data/app-python/*" { + capabilities = ["read"] +} +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec -it vault-0 -- /bin/sh -c "export VAULT_TOKEN=root; vault read auth/kubernetes/role/app-python" +Key Value +--- ----- +alias_name_source serviceaccount_uid +bound_service_account_names [default] +bound_service_account_namespace_selector n/a +bound_service_account_namespaces [default] +policies [app-python] +token_bound_cidrs [] +token_explicit_max_ttl 0s +token_max_ttl 0s +token_no_default_policy false +token_num_uses 0 +token_period 0s +token_policies [app-python] +token_ttl 1h +token_type default +ttl 1h +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> +``` + +### Proof of secret injection (file exists + content) + +```powershell +kubectl exec -it app-python-9f578645d-xvmn4 -c app-python -- ls -la /vault/secrets/ +``` + +```text +total 8 +drwxrwxrwt 2 root root 60 Apr 4 18:53 . +drwxr-xr-x 3 root root 4096 Apr 4 18:53 .. +-rw-r--r-- 1 100 appuser 173 Apr 4 18:53 config +``` + +```powershell +kubectl exec -it app-python-9f578645d-xvmn4 -c app-python -- cat /vault/secrets/config +``` + +```text +data: map[password:vault-pass username:vault-user] +metadata: map[created_time:2026-04-04T18:19:33.744296466Z custom_metadata: deletion_time: destroyed:false version:1] +``` + +### Sidecar injection pattern (summary) + +Vault Agent runs as a sidecar container, authenticates using the pod’s ServiceAccount, fetches secrets from Vault, and writes them into a shared volume at `/vault/secrets/`. The application container reads secrets from files instead of environment variables. + +--- + +## Security Analysis + +### K8s Secrets vs Vault + +| Feature | K8s Secrets | Vault | +|--------|-------------|-------| +| Encryption at rest | Optional | ✅ Built‑in | +| Rotation | Manual | ✅ Automated | +| Audit | Limited | ✅ Full audit | +| Dynamic secrets | ❌ No | ✅ Yes | +| Multi‑platform | ❌ K8s only | ✅ Yes | + +### When to use each + +- **K8s Secrets:** small apps, internal environments, low complexity. +- **Vault:** production, compliance, multi‑env, rotation/audit needed. + +### Production recommendations + +- Enable **etcd encryption at rest**. +- Use **RBAC least privilege**. +- Use **Vault** for sensitive/rotating credentials. +- Never commit real secrets to Git. \ No newline at end of file diff --git a/k8s/STATEFULSET.md b/k8s/STATEFULSET.md new file mode 100644 index 0000000000..2c9a902477 --- /dev/null +++ b/k8s/STATEFULSET.md @@ -0,0 +1,156 @@ +# Lab 15 — StatefulSets & Persistent Storage + +## 1. StatefulSet Overview + +### 1.1 StatefulSet Overview: Why StatefulSet? +StatefulSet is a specialized workload controller used to manage applications that require a persistent "identity" or state. Unlike standard Deployments, which treat pods as completely interchangeable and "cattle," StatefulSets treat them as "pets"—unique instances that must be managed with care. + +**StatefulSets provide critical guarantees:** +- **Stable Network ID:** A pod will always have the same hostname (e.g., `app-0`), even after rescheduling. +- **Stable Storage:** Each pod maps to its own Persistent Volume (PV). If a pod is deleted and recreated, it re-attaches to the exact same volume it had before. +- **Ordered Operations:** Pods are started, updated, and deleted in a specific order (0, 1, 2...), which is essential for database clusters that need to establish a quorum. + +### 1.2 Comparison: Deployment vs StatefulSet + +| Feature | Deployment (Stateless) | StatefulSet (Stateful) | +|:---|:---|:---| +| **Pod Naming** | Random hash suffix (`app-xyz123`) | Fixed ordinal index (`app-0`, `app-1`) | +| **Storage Model** | Shared volume or ephemeral disks | **Dedicated volume per pod instance** | +| **Network Identity**| Dynamic (access via Service IP) | Fixed DNS name for each specific pod | +| **Scaling** | Parallel and immediate | Sequential and ordered (0 -> 1 -> 2) | +| **Best For** | Web APIs, workers, stateless apps | Databases (PostgreSQL), Queues (Kafka) | + +### 1.3 Headless Services & DNS +To enable stable networking, StatefulSets require a **Headless Service** (`clusterIP: None`). +- **Function:** Unlike a normal service that load-balances traffic, a Headless Service allows the user (or other pods) to discover the direct IP addresses of all pods in the set. +- **DNS Resolution:** With a Headless Service named `app-headless`, the DNS record for `app-0` becomes `app-0.app-headless.default.svc.cluster.local`. This is how database nodes find each other to synchronize data. + +--- + +## 2. Resource Verification + +### Implementation: Convert Deployment to StatefulSet + +To transform the application into a stateful workload, the following changes were implemented in the Helm chart: + +#### 2.1 StatefulSet Template +Created [`k8s/app-python/templates/statefulset.yaml`](k8s/app-python/templates/statefulset.yaml) which defines: +- `kind: StatefulSet` +- `serviceName`: Points to the headless service for stable DNS. +- `volumeClaimTemplates`: Automatically provisions a unique PersistentVolumeClaim (PVC) for each pod instance. + +#### 2.2 Headless Service +Created [`k8s/app-python/templates/service-headless.yaml`](k8s/app-python/templates/service-headless.yaml) with `clusterIP: None`. This service is responsible for the network identity of the pods. + +#### 2.3 VolumeClaimTemplates Configuration +Each pod now has independent storage. The configuration is driven by `values.yaml`: +```yaml +persistence: + enabled: true + size: 100Mi +``` + +``` +kubectl get po,sts,svc,pvc +``` + +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get po,sts,svc,pvc +NAME READY STATUS RESTARTS AGE +pod/app-python-sts-0 1/1 Running 0 28s +pod/app-python-sts-1 1/1 Running 0 22s +pod/app-python-sts-2 1/1 Running 0 18s + +NAME READY AGE +statefulset.apps/app-python-sts 3/3 28s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) + AGE +service/app-python-sts NodePort 10.111.77.34 80:30090/TCP 28s +service/app-python-sts-headless ClusterIP None 80/TCP + 28s + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE +persistentvolumeclaim/data-app-python-sts-0 Bound pvc-f58709a2-c710-441d-88db-dd83c60b404e 100Mi RWO standard 28s +persistentvolumeclaim/data-app-python-sts-1 Bound pvc-c051cb8a-dff1-4464-a025-da09e697b2d4 100Mi RWO standard 22s +persistentvolumeclaim/data-app-python-sts-2 Bound pvc-4b652921-9ef2-425c-8299-8b73d189d13f 100Mi RWO standard 18s +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> + +``` + +## 3. Network Identity +Each pod in the StatefulSet is assigned a stable DNS name following the pattern: +`...svc.cluster.local` + +**Evidence:** +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-0 -- getent hosts app-python-sts-1.app-python-sts-headless.default.svc.cluster.local +10.244.1.19 app-python-sts-1.app-python-sts-headless.default.svc.cluster.local + +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-0 -- getent hosts app-python-sts-2.app-python-sts-headless.default.svc.cluster.local +10.244.1.20 app-python-sts-2.app-python-sts-headless.default.svc.cluster.local +``` + +## 4. Per-Pod Storage Evidence +By accessing pods individually via port-forwarding, I verified that they maintain unique data on their dedicated volumes. + +**Verification:** +1. Accessed `app-python-sts-0` via port-forwarding and refreshed the page 4 times. +2. Accessed `app-python-sts-1` via port-forwarding and refreshed the page 1 time. + +``` +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl port-forward pod/app-python-sts-0 8080:5000 +Forwarding from 127.0.0.1:8080 -> 5000 +Forwarding from [::1]:8080 -> 5000 +Handling connection for 8080 +Handling connection for 8080 +Handling connection for 8080 +Handling connection for 8080 +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl port-forward pod/app-python-sts-1 8081:5000 +Forwarding from 127.0.0.1:8081 -> 5000 +Forwarding from [::1]:8081 -> 5000 +Handling connection for 8081 +``` + +**Evidence:** +```powershell +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-0 -- cat /data/visits +4 +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-1 -- cat /data/visits +1 +``` +This confirms that `volumeClaimTemplates` correctly provisioned independent storage for each pod ordinal. + +## 5. Persistence Test + +The goal of this test was to verify that data survives pod deletion and is correctly re-attached because of the stable identity of instances in a StatefulSet. + +**Steps and Evidence:** + +1. **Check value before deletion** +2. **Delete the pod instance** +3. **Verify pod recreation** +4. **Verify data persistence**: +``` +так? +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-0 -- cat /data/visits +4 +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl delete pod app-python-sts-0 +pod "app-python-sts-0" deleted +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get po -w +NAME READY STATUS RESTARTS AGE +app-python-sts-0 1/1 Terminating 0 13m +app-python-sts-1 1/1 Running 0 13m +app-python-sts-2 1/1 Running 0 13m + +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl get po -w +NAME READY STATUS RESTARTS AGE +app-python-sts-0 1/1 Running 0 7s +app-python-sts-1 1/1 Running 0 13m +app-python-sts-2 1/1 Running 0 13m +(venv) PS D:\INNOPOLIS\DEVOPS ENGINEERING\DevOps-course> kubectl exec app-python-sts-0 -- cat /data/visits +4 +``` + +**Conclusion:** +The test confirms that the PVC `data-app-python-sts-0` is strictly bound to the pod instance index `0`. When the pod was deleted, the storage remained intact and was automatically remounted to the new pod, successfully preserving the application state. \ No newline at end of file diff --git a/k8s/app-python/.helmignore b/k8s/app-python/.helmignore new file mode 100644 index 0000000000..0e8a0eb36f --- /dev/null +++ b/k8s/app-python/.helmignore @@ -0,0 +1,23 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*.orig +*~ +# Various IDEs +.project +.idea/ +*.tmproj +.vscode/ diff --git a/k8s/app-python/Chart.yaml b/k8s/app-python/Chart.yaml new file mode 100644 index 0000000000..413a965729 --- /dev/null +++ b/k8s/app-python/Chart.yaml @@ -0,0 +1,10 @@ +apiVersion: v2 +name: app-python +description: Helm chart for the DevOps course Python info service +type: application + +# Chart version (SemVer) – increment when chart changes +version: 0.1.0 + +# Application version – matches your app version +appVersion: "1.0.0" \ No newline at end of file diff --git a/k8s/app-python/files/config.json b/k8s/app-python/files/config.json new file mode 100644 index 0000000000..7471188ab9 --- /dev/null +++ b/k8s/app-python/files/config.json @@ -0,0 +1,18 @@ +{ + "application": { + "name": "devops-info-service", + "version": "1.0.0", + "environment": "production", + "description": "DevOps course info service" + }, + "features": { + "visits_tracking": true, + "metrics_enabled": true, + "debug_mode": false + }, + "settings": { + "log_level": "INFO", + "cache_ttl": 3600, + "max_connections": 100 + } +} diff --git a/k8s/app-python/templates/NOTES.txt b/k8s/app-python/templates/NOTES.txt new file mode 100644 index 0000000000..0f76f6220b --- /dev/null +++ b/k8s/app-python/templates/NOTES.txt @@ -0,0 +1,35 @@ +1. Get the application URL by running these commands: +{{- if .Values.httpRoute.enabled }} +{{- if .Values.httpRoute.hostnames }} + export APP_HOSTNAME={{ .Values.httpRoute.hostnames | first }} +{{- else }} + export APP_HOSTNAME=$(kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o jsonpath="{.spec.listeners[0].hostname}") + {{- end }} +{{- if and .Values.httpRoute.rules (first .Values.httpRoute.rules).matches (first (first .Values.httpRoute.rules).matches).path.value }} + echo "Visit http://$APP_HOSTNAME{{ (first (first .Values.httpRoute.rules).matches).path.value }} to use your application" + + NOTE: Your HTTPRoute depends on the listener configuration of your gateway and your HTTPRoute rules. + The rules can be set for path, method, header and query parameters. + You can check the gateway configuration with 'kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o yaml' +{{- end }} +{{- else if .Values.ingress.enabled }} +{{- range $host := .Values.ingress.hosts }} + {{- range .paths }} + http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }} + {{- end }} +{{- end }} +{{- else if contains "NodePort" .Values.service.type }} + export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "app-python.fullname" . }}) + export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") + echo http://$NODE_IP:$NODE_PORT +{{- else if contains "LoadBalancer" .Values.service.type }} + NOTE: It may take a few minutes for the LoadBalancer IP to be available. + You can watch its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "app-python.fullname" . }}' + export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "app-python.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}") + echo http://$SERVICE_IP:{{ .Values.service.port }} +{{- else if contains "ClusterIP" .Values.service.type }} + export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "app-python.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") + export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") + echo "Visit http://127.0.0.1:8080 to use your application" + kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT +{{- end }} diff --git a/k8s/app-python/templates/_helpers.tpl b/k8s/app-python/templates/_helpers.tpl new file mode 100644 index 0000000000..b39b9e5cc3 --- /dev/null +++ b/k8s/app-python/templates/_helpers.tpl @@ -0,0 +1,62 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "app-python.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "app-python.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "app-python.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "app-python.labels" -}} +helm.sh/chart: {{ include "app-python.chart" . }} +{{ include "app-python.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "app-python.selectorLabels" -}} +app.kubernetes.io/name: {{ include "app-python.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "app-python.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "app-python.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/k8s/app-python/templates/configmap.yaml b/k8s/app-python/templates/configmap.yaml new file mode 100644 index 0000000000..3b826b1bd1 --- /dev/null +++ b/k8s/app-python/templates/configmap.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "app-python.fullname" . }}-config + labels: + {{- include "app-python.labels" . | nindent 4 }} +data: + config.json: |- +{{ .Files.Get "files/config.json" | indent 4 }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "app-python.fullname" . }}-env + labels: + {{- include "app-python.labels" . | nindent 4 }} +data: + APP_ENV: {{ .Values.configmap.environment | quote }} + LOG_LEVEL: {{ .Values.configmap.logLevel | quote }} + CACHE_TTL: {{ .Values.configmap.cacheTTL | quote }} diff --git a/k8s/app-python/templates/deployment.yaml b/k8s/app-python/templates/deployment.yaml new file mode 100644 index 0000000000..05d6e1f10d --- /dev/null +++ b/k8s/app-python/templates/deployment.yaml @@ -0,0 +1,86 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "app-python.fullname" . }} + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "app-python.selectorLabels" . | nindent 6 }} + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + template: + metadata: + labels: + {{- include "app-python.selectorLabels" . | nindent 8 }} + {{- if .Values.vault.enabled }} + annotations: + vault.hashicorp.com/agent-inject: "true" + vault.hashicorp.com/role: {{ .Values.vault.role | quote }} + vault.hashicorp.com/agent-inject-secret-config: {{ .Values.vault.secretPath | quote }} + {{- end }} + spec: + containers: + - name: {{ .Chart.Name }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.service.targetPort }} + protocol: TCP + + # ConfigMap as Environment Variables + envFrom: + - configMapRef: + name: {{ include "app-python.fullname" . }}-env + - secretRef: + name: {{ include "app-python.fullname" . }}-secret + + # Pod-specific environment variables + env: + - name: PORT + value: {{ .Values.env.port | quote }} + - name: DATA_DIR + value: "/data" + + # ConfigMap and PVC Volume Mounts + volumeMounts: + - name: config-volume + mountPath: /config + - name: data-volume + mountPath: /data + + resources: + {{- toYaml .Values.resources | nindent 12 }} + + {{- if .Values.livenessProbe.enabled }} + livenessProbe: + httpGet: + path: {{ .Values.livenessProbe.path }} + port: {{ .Values.service.targetPort }} + initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.livenessProbe.periodSeconds }} + {{- end }} + + {{- if .Values.readinessProbe.enabled }} + readinessProbe: + httpGet: + path: {{ .Values.readinessProbe.path }} + port: {{ .Values.service.targetPort }} + initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.readinessProbe.periodSeconds }} + {{- end }} + + # Volumes + volumes: + - name: config-volume + configMap: + name: {{ include "app-python.fullname" . }}-config + - name: data-volume + persistentVolumeClaim: + claimName: {{ include "app-python.fullname" . }}-data diff --git a/k8s/app-python/templates/hooks/post-install-job.yaml b/k8s/app-python/templates/hooks/post-install-job.yaml new file mode 100644 index 0000000000..5b2338a21a --- /dev/null +++ b/k8s/app-python/templates/hooks/post-install-job.yaml @@ -0,0 +1,28 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: "{{ include "app-python.fullname" . }}-post-install" + labels: + {{- include "app-python.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": post-install + "helm.sh/hook-weight": "5" + "helm.sh/hook-delete-policy": hook-succeeded +spec: + template: + metadata: + name: "{{ include "app-python.fullname" . }}-post-install" + labels: + {{- include "app-python.labels" . | nindent 8 }} + spec: + restartPolicy: Never + containers: + - name: post-install-job + image: busybox + command: + - sh + - -c + - | + echo "Post-install smoke test for {{ .Release.Name }}"; + sleep 5; + echo "Post-install hook completed successfully" \ No newline at end of file diff --git a/k8s/app-python/templates/hooks/pre-install-job.yaml b/k8s/app-python/templates/hooks/pre-install-job.yaml new file mode 100644 index 0000000000..4dd660d44e --- /dev/null +++ b/k8s/app-python/templates/hooks/pre-install-job.yaml @@ -0,0 +1,28 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: "{{ include "app-python.fullname" . }}-pre-install" + labels: + {{- include "app-python.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": pre-install + "helm.sh/hook-weight": "-5" + "helm.sh/hook-delete-policy": hook-succeeded +spec: + template: + metadata: + name: "{{ include "app-python.fullname" . }}-pre-install" + labels: + {{- include "app-python.labels" . | nindent 8 }} + spec: + restartPolicy: Never + containers: + - name: pre-install-job + image: busybox + command: + - sh + - -c + - | + echo "Pre-install hook running for release {{ .Release.Name }}"; + sleep 5; + echo "Pre-install hook completed" \ No newline at end of file diff --git a/k8s/app-python/templates/pvc.yaml b/k8s/app-python/templates/pvc.yaml new file mode 100644 index 0000000000..1d145caf47 --- /dev/null +++ b/k8s/app-python/templates/pvc.yaml @@ -0,0 +1,17 @@ +{{- if .Values.persistence.enabled }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "app-python.fullname" . }}-data + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: {{ .Values.persistence.size }} + {{- if .Values.persistence.storageClass }} + storageClassName: {{ .Values.persistence.storageClass }} + {{- end }} +{{- end }} diff --git a/k8s/app-python/templates/rollout.yaml b/k8s/app-python/templates/rollout.yaml new file mode 100644 index 0000000000..12a9a33097 --- /dev/null +++ b/k8s/app-python/templates/rollout.yaml @@ -0,0 +1,65 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Rollout +metadata: + name: {{ include "app-python.fullname" . }} + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "app-python.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "app-python.selectorLabels" . | nindent 8 }} + {{- if .Values.vault.enabled }} + annotations: + vault.hashicorp.com/agent-inject: "true" + vault.hashicorp.com/role: {{ .Values.vault.role | quote }} + vault.hashicorp.com/agent-inject-secret-config: {{ .Values.vault.secretPath | quote }} + {{- end }} + spec: + containers: + - name: {{ .Chart.Name }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.service.targetPort }} + protocol: TCP + env: + - name: PORT + value: {{ .Values.env.port | quote }} + - name: DATA_DIR + value: {{ .Values.env.dataDir | quote }} + livenessProbe: + httpGet: + path: /health + port: http + initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.livenessProbe.periodSeconds }} + readinessProbe: + httpGet: + path: /health + port: http + initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.readinessProbe.periodSeconds }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- if .Values.persistence.enabled }} + volumeMounts: + - name: data + mountPath: /data + {{- end }} + {{- if .Values.persistence.enabled }} + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ include "app-python.fullname" . }}-data + {{- end }} + strategy: + blueGreen: + activeService: {{ include "app-python.fullname" . }} + previewService: {{ include "app-python.fullname" . }}-preview + autoPromotionEnabled: false diff --git a/k8s/app-python/templates/secrets.yaml b/k8s/app-python/templates/secrets.yaml new file mode 100644 index 0000000000..43ee4c6f1f --- /dev/null +++ b/k8s/app-python/templates/secrets.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "app-python.fullname" . }}-secret + labels: + {{- include "app-python.labels" . | nindent 4 }} +type: Opaque +stringData: + username: {{ .Values.secret.username | quote }} + password: {{ .Values.secret.password | quote }} diff --git a/k8s/app-python/templates/service-headless.yaml b/k8s/app-python/templates/service-headless.yaml new file mode 100644 index 0000000000..f1cb2d23e2 --- /dev/null +++ b/k8s/app-python/templates/service-headless.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "app-python.fullname" . }}-headless + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + clusterIP: None + selector: + {{- include "app-python.selectorLabels" . | nindent 4 }} + ports: + - port: {{ .Values.service.port }} + targetPort: {{ .Values.service.targetPort }} + protocol: TCP + name: http \ No newline at end of file diff --git a/k8s/app-python/templates/service-preview.yaml b/k8s/app-python/templates/service-preview.yaml new file mode 100644 index 0000000000..20cea757ca --- /dev/null +++ b/k8s/app-python/templates/service-preview.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "app-python.fullname" . }}-preview + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: {{ .Values.service.targetPort }} + protocol: TCP + name: http + selector: + {{- include "app-python.selectorLabels" . | nindent 4 }} diff --git a/k8s/app-python/templates/service.yaml b/k8s/app-python/templates/service.yaml new file mode 100644 index 0000000000..528e734dc7 --- /dev/null +++ b/k8s/app-python/templates/service.yaml @@ -0,0 +1,17 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "app-python.fullname" . }} + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + selector: + {{- include "app-python.selectorLabels" . | nindent 4 }} + ports: + - protocol: TCP + port: {{ .Values.service.port }} + targetPort: {{ .Values.service.targetPort }} + {{- if eq .Values.service.type "NodePort" }} + nodePort: {{ .Values.service.nodePort }} + {{- end }} diff --git a/k8s/app-python/templates/statefulset.yaml b/k8s/app-python/templates/statefulset.yaml new file mode 100644 index 0000000000..469441c39e --- /dev/null +++ b/k8s/app-python/templates/statefulset.yaml @@ -0,0 +1,60 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "app-python.fullname" . }} + labels: + {{- include "app-python.labels" . | nindent 4 }} +spec: + serviceName: {{ include "app-python.fullname" . }}-headless + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "app-python.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "app-python.selectorLabels" . | nindent 8 }} + spec: + initContainers: + # Init Container 1: Download file + - name: init-download + image: busybox:1.36 + command: ['sh', '-c', 'wget -O /work-dir/config.txt https://raw.githubusercontent.com/kubernetes/kubernetes/master/README.md && echo "Config downloaded successfully"'] + volumeMounts: + - name: workdir + mountPath: /work-dir + + # Init Container 2: Wait for Vault service + - name: wait-for-vault + image: busybox:1.28 + command: ['sh', '-c', 'until nslookup vault.default.svc.cluster.local; do echo waiting for vault; sleep 2; done'] + + containers: + - name: {{ .Chart.Name }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + ports: + - name: http + containerPort: {{ .Values.service.targetPort }} + env: + - name: PORT + value: {{ .Values.service.targetPort | quote }} + - name: DATA_DIR + value: "/data" + volumeMounts: + - name: data + mountPath: /data + - name: workdir + mountPath: /shared-config + + volumes: + - name: workdir + emptyDir: {} + + volumeClaimTemplates: + - metadata: + name: data + spec: + accessModes: [ "ReadWriteOnce" ] + resources: + requests: + storage: {{ .Values.persistence.size | default "100Mi" }} \ No newline at end of file diff --git a/k8s/app-python/values-dev.yaml b/k8s/app-python/values-dev.yaml new file mode 100644 index 0000000000..4824ddfc73 --- /dev/null +++ b/k8s/app-python/values-dev.yaml @@ -0,0 +1,25 @@ +replicaCount: 1 + +image: + # dev can use 'latest' for faster iteration + tag: "latest" + +service: + type: NodePort + nodePort: 30081 + +resources: + requests: + cpu: "50m" + memory: "64Mi" + limits: + cpu: "100m" + memory: "128Mi" + +livenessProbe: + initialDelaySeconds: 5 + periodSeconds: 10 + +readinessProbe: + initialDelaySeconds: 3 + periodSeconds: 5 \ No newline at end of file diff --git a/k8s/app-python/values-prod.yaml b/k8s/app-python/values-prod.yaml new file mode 100644 index 0000000000..2fdbde305b --- /dev/null +++ b/k8s/app-python/values-prod.yaml @@ -0,0 +1,25 @@ +replicaCount: 5 + +image: + # prod should use a fixed tag; if у тебя есть конкретный тег, впиши его + tag: "latest" + +service: + type: NodePort + nodePort: 30082 + +resources: + requests: + cpu: "200m" + memory: "256Mi" + limits: + cpu: "500m" + memory: "512Mi" + +livenessProbe: + initialDelaySeconds: 30 + periodSeconds: 5 + +readinessProbe: + initialDelaySeconds: 10 + periodSeconds: 3 \ No newline at end of file diff --git a/k8s/app-python/values.yaml b/k8s/app-python/values.yaml new file mode 100644 index 0000000000..26f7f0a37f --- /dev/null +++ b/k8s/app-python/values.yaml @@ -0,0 +1,61 @@ +replicaCount: 3 + +image: + repository: sunflye/devops-info-service + tag: "latest" + pullPolicy: IfNotPresent + +service: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: 30090 + +resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "200m" + memory: "256Mi" + +livenessProbe: + enabled: true + path: /health + initialDelaySeconds: 10 + periodSeconds: 5 + +readinessProbe: + enabled: true + path: /health + initialDelaySeconds: 5 + periodSeconds: 3 + +env: + port: "5000" + dataDir: "/data" + +httpRoute: + enabled: false + +ingress: + enabled: false + +secret: + username: "placeholder-user" + password: "placeholder-pass" + +vault: + enabled: false + role: "app-python" + secretPath: "secret/data/app-python/config" + +configmap: + environment: "production" + logLevel: "INFO" + cacheTTL: "3600" + +persistence: + enabled: true + size: 100Mi + storageClass: "" diff --git a/k8s/argocd/application-dev.yaml b/k8s/argocd/application-dev.yaml new file mode 100644 index 0000000000..154eb5c76b --- /dev/null +++ b/k8s/argocd/application-dev.yaml @@ -0,0 +1,23 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app-dev + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/sunflye/DevOps-course.git + targetRevision: lab13 + path: k8s/app-python + helm: + valueFiles: + - values-dev.yaml + destination: + server: https://kubernetes.default.svc + namespace: dev + syncPolicy: + automated: + prune: true + selfHeal: true + syncOptions: + - CreateNamespace=true diff --git a/k8s/argocd/application-prod.yaml b/k8s/argocd/application-prod.yaml new file mode 100644 index 0000000000..160174db3d --- /dev/null +++ b/k8s/argocd/application-prod.yaml @@ -0,0 +1,20 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app-prod + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/sunflye/DevOps-course.git + targetRevision: lab13 + path: k8s/app-python + helm: + valueFiles: + - values-prod.yaml + destination: + server: https://kubernetes.default.svc + namespace: prod + syncPolicy: + syncOptions: + - CreateNamespace=true diff --git a/k8s/argocd/application.yaml b/k8s/argocd/application.yaml new file mode 100644 index 0000000000..e0453e0987 --- /dev/null +++ b/k8s/argocd/application.yaml @@ -0,0 +1,20 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/sunflye/DevOps-course.git + targetRevision: lab13 + path: k8s/app-python + helm: + valueFiles: + - values.yaml + destination: + server: https://kubernetes.default.svc + namespace: default + syncPolicy: + syncOptions: + - CreateNamespace=true diff --git a/k8s/deployment.yml b/k8s/deployment.yml new file mode 100644 index 0000000000..e948947746 --- /dev/null +++ b/k8s/deployment.yml @@ -0,0 +1,50 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: app-python + labels: + app: app-python +spec: + replicas: 5 + selector: + matchLabels: + app: app-python + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + template: + metadata: + labels: + app: app-python + spec: + containers: + - name: app-python + image: sunflye/devops-info-service:latest + ports: + - containerPort: 5000 + env: + - name: PORT + value: "5000" + - name: DEMO_VAR + value: "v2" + resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "200m" + memory: "256Mi" + livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 10 + periodSeconds: 5 + readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 3 \ No newline at end of file diff --git a/k8s/service.yml b/k8s/service.yml new file mode 100644 index 0000000000..5a52b8e6ed --- /dev/null +++ b/k8s/service.yml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: app-python-service + labels: + app: app-python +spec: + type: NodePort + selector: + app: app-python + ports: + - protocol: TCP + port: 80 + targetPort: 5000 + nodePort: 30080 \ No newline at end of file diff --git a/monitoring/dashboard/application_metrics_lab8.json b/monitoring/dashboard/application_metrics_lab8.json new file mode 100644 index 0000000000..f33faed4d8 --- /dev/null +++ b/monitoring/dashboard/application_metrics_lab8.json @@ -0,0 +1,636 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "links": [], + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 7, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "auto", + "percentChangeColorMode": "standard", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "textMode": "auto", + "wideLayout": true + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "up{job=\"app\", instance=\"app-python:5000\"}", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Uptime", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 0 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "sum(rate(http_requests_total[5m])) by (endpoint)", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Request Rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + } + }, + "mappings": [] + }, + "overrides": [ + { + "__systemRef": "hideSeriesFrom", + "matcher": { + "id": "byNames", + "options": { + "mode": "exclude", + "names": [ + "200" + ], + "prefix": "All except:", + "readOnly": true + } + }, + "properties": [ + { + "id": "custom.hideFrom", + "value": { + "legend": false, + "tooltip": true, + "viz": true + } + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 8 + }, + "id": 6, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "pieType": "pie", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "sort": "desc", + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "sum by (status) (rate(http_requests_total[5m]))", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Status Code Distribution", + "type": "piechart" + }, + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 8 + }, + "id": 5, + "options": { + "minVizHeight": 75, + "minVizWidth": 75, + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "showThresholdLabels": false, + "showThresholdMarkers": true, + "sizing": "auto" + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "http_requests_in_progress", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Active Requests", + "type": "gauge" + }, + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "custom": { + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "scaleDistribution": { + "type": "linear" + } + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 16 + }, + "id": 4, + "options": { + "calculate": false, + "cellGap": 1, + "color": { + "exponent": 0.5, + "fill": "dark-orange", + "mode": "scheme", + "reverse": false, + "scale": "exponential", + "scheme": "Oranges", + "steps": 64 + }, + "exemplars": { + "color": "rgba(255,0,255,0.7)" + }, + "filterValues": { + "le": 1e-9 + }, + "legend": { + "show": true + }, + "rowsFrame": { + "layout": "auto" + }, + "tooltip": { + "mode": "single", + "showColorScale": false, + "yHistogram": false + }, + "yAxis": { + "axisPlacement": "left", + "reverse": false + } + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "rate(http_request_duration_seconds_bucket[5m])", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Request Duration Heatmap", + "type": "heatmap" + }, + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 16 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Request Duration p95", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 24 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.3.1", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "dfg7jvxds09hcd" + }, + "editorMode": "code", + "expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m]))", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Error Rate", + "type": "timeseries" + } + ], + "preload": false, + "schemaVersion": 42, + "tags": [], + "templating": { + "list": [] + }, + "time": { + "from": "now-1h", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "Application Metrics", + "uid": "ad7hdnw", + "version": 10 +} \ No newline at end of file diff --git a/monitoring/docker-compose.yml b/monitoring/docker-compose.yml new file mode 100644 index 0000000000..b3d055e0cb --- /dev/null +++ b/monitoring/docker-compose.yml @@ -0,0 +1,156 @@ +version: '3.8' + +services: + loki: + image: grafana/loki:${LOKI_VERSION:-3.0.0} + ports: + - "3100:3100" + volumes: + - ./loki/config.yml:/etc/loki/config.yml + - loki-data:/loki + command: -config.file=/etc/loki/config.yml + networks: + - logging + healthcheck: + test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:3100/ready || exit 1"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + reservations: + cpus: '0.5' + memory: 512M + + promtail: + image: grafana/promtail:${PROMTAIL_VERSION:-3.0.0} + ports: + - "9080:9080" + volumes: + - ./promtail/config.yml:/etc/promtail/config.yml + - /var/lib/docker/containers:/var/lib/docker/containers:ro + - /var/run/docker.sock:/var/run/docker.sock:ro + command: -config.file=/etc/promtail/config.yml + networks: + - logging + depends_on: + - loki + deploy: + resources: + limits: + cpus: '0.5' + memory: 512M + reservations: + cpus: '0.25' + memory: 256M + healthcheck: + test: ["CMD-SHELL", "[ \"$(cat /proc/1/comm)\" = \"promtail\" ] || exit 1"] + interval: 10s + timeout: 5s + retries: 6 + start_period: 15s + restart: unless-stopped + + grafana: + image: grafana/grafana:${GRAFANA_VERSION:-12.3.1} + ports: + - "3000:3000" + volumes: + - grafana-data:/var/lib/grafana + networks: + - logging + environment: + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD} + GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER} + GF_SECURITY_ALLOW_EMBEDDING: "false" + GF_USERS_ALLOW_SIGN_UP: "false" + depends_on: + - loki + healthcheck: + test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:3000/api/health || exit 1"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 15s + deploy: + resources: + limits: + cpus: '0.5' + memory: 512M + reservations: + cpus: '0.25' + memory: 256M + prometheus: + image: prom/prometheus:v3.9.0 + container_name: prometheus + ports: + - "9090:9090" + volumes: + - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml + - prometheus-data:/prometheus + command: + - '--config.file=/etc/prometheus/prometheus.yml' + - '--storage.tsdb.retention.time=15d' + - '--storage.tsdb.retention.size=10GB' + networks: + - logging + healthcheck: + test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:9090/-/healthy || exit 1"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + reservations: + cpus: '0.5' + memory: 512M + depends_on: + - loki + - grafana + + app-python: + image: sunflye/devops-info-service:latest + ports: + - "8000:5000" + environment: + HOST: "0.0.0.0" + PORT: "5000" + networks: + - logging + labels: + logging: "promtail" + app: "devops-python" + depends_on: + - promtail + healthcheck: + test: ["CMD", "python", "-c", "import socket; s=socket.socket(); s.connect(('127.0.0.1', 5000)); s.close()"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 5s + deploy: + resources: + limits: + cpus: '0.5' + memory: 256M + reservations: + cpus: '0.25' + memory: 128M + +volumes: + loki-data: + grafana-data: + prometheus-data: + +networks: + logging: + driver: bridge \ No newline at end of file diff --git a/monitoring/docs/LAB07.md b/monitoring/docs/LAB07.md new file mode 100644 index 0000000000..8a0937e7e8 --- /dev/null +++ b/monitoring/docs/LAB07.md @@ -0,0 +1,446 @@ +# Lab 7 — Observability & Logging with Loki Stack + + +## 1. Architecture + +```plaintext +┌─────────────────────────────────────────────────────────────┐ +│ Docker Host │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ app-python │ │ other apps │ │ +│ │ (port 8000) │ │ (optional) │ │ +│ │ JSON logs │ │ JSON logs │ │ +│ └──────┬───────┘ └──────┬───────┘ │ +│ │ │ │ +│ └──────────────────┼ │ +│ │ │ +│ ┌──────────────▼───────────────┐ │ +│ │ Promtail Agent │ │ +│ │ (Log Collector, port 9080) │ │ +│ └──────────────┬───────────────┘ │ +│ │ Push Logs (HTTP/gRPC) │ +│ ┌──────────────▼───────────────┐ │ +│ │ Loki │ │ +│ │ (Log Storage, port 3100) │ │ +│ └──────────────┬───────────────┘ │ +│ │ Query Logs (LogQL) │ +│ ┌──────────────▼───────────────┐ │ +│ │ Grafana │ │ +│ │(Visualization, port 3000) │ │ +│ └──────────────────────────────┘ │ +│ │ +│ Network: logging (bridge) │ +└─────────────────────────────────────────────────────────────┘ +``` + +**Data flow:** +Application logs → Promtail (collects, labels, pushes) → Loki (stores, indexes) → Grafana (visualizes, queries) + + +## 2. Setup Guide + +### Step 1: Project Structure + +Create the directory structure: + +``` +mkdir -p monitoring/{loki,promtail,docs} +cd monitoring +``` + +### Step 2: Create Environment Variables + +File: `monitoring/.env` +```ini +GRAFANA_ADMIN_USER=admin +GRAFANA_ADMIN_PASSWORD=secure_password_here +LOKI_VERSION=3.0.0 +PROMTAIL_VERSION=3.0.0 +GRAFANA_VERSION=12.3.1 +COMPOSE_PROJECT_NAME=logging_stack +``` + +### Step 3: Create .gitignore + +File: `monitoring/.gitignore` +``` +.env +.env.local +terraform.tfstate* +__pycache__/ +.DS_Store +``` + +### Step 4: Deploy Services + +``` +cd monitoring + +# Start all services in background +docker compose up -d + +# Verify health status +docker compose ps + +# Check logs if needed +docker compose logs -f loki +docker compose logs -f promtail +docker compose logs -f grafana +``` + +## 3. Configuration + +### Loki (`loki/config.yml`) + +- **TSDB storage** (`store: tsdb`): Enables fast queries and efficient log storage, recommended for Loki 3.0+. +- **Filesystem backend** (`object_store: filesystem`): Simple, reliable storage for single-node deployments. +- **Retention** (`retention_period: 168h`): Keeps logs for 7 days, balancing storage cost and troubleshooting needs. +- **Schema v13**: Latest schema for Loki, ensures compatibility and performance. +- **Inmemory ring** (`kvstore: store: inmemory`): No external dependencies (like Consul), ideal for single-node setups. + +**Example snippet:** +```yaml +schema_config: + configs: + - from: 2020-10-24 + store: tsdb + object_store: filesystem + schema: v13 +limits_config: + retention_period: 168h +common: + ring: + kvstore: + store: inmemory +``` +### Promtail (promtail/config.yml) +- **Docker service discovery (docker_sd_configs)**: Automatically finds running containers, no manual config needed. +- **Relabeling:** Extracts useful labels (app, container_name, image, job) from Docker metadata for log filtering and querying. +- **Low cardinality labels:** Avoids performance issues by not indexing unique values (like container IDs). +- **Positions file:** Tracks log read progress, prevents duplicate ingestion. + +**Example snippet:** +```yaml +scrape_configs: + - job_name: docker + docker_sd_configs: + - host: unix:///var/run/docker.sock + refresh_interval: 5s + relabel_configs: + - source_labels: ['__meta_docker_container_name'] + regex: '/(.+)' + target_label: 'container_name' + - source_labels: ['__meta_docker_container_label_app'] + target_label: 'app' + - source_labels: ['__meta_docker_image_name'] + target_label: 'image' +positions: + filename: /tmp/positions.yaml +``` +### Why: + +- Docker SD + relabeling = automatic, scalable log collection. +- Only meaningful labels indexed for efficient LogQL queries. +- Retention and storage settings ensure logs are available but not wasteful. + +## Task 1 — Deploy Loki Stack +![loki](./screenshots/grafana_logs_task1.png) + +## 4. Application Logging + +### Implementation + +- Used a custom `JSONFormatter` class in `app_python/app.py` to output logs in structured JSON format. +- Configured Python's `logging` module to use this formatter for all log messages. +- Logs include fields: `timestamp`, `level`, `logger`, `message`, and (if available) `endpoint`, `method`, `status_code`, `response_time`, `request_id`, and exception info. +- Logging occurs for: + - Application startup + - Each HTTP request (`@app.before_request`) + - Each response (`@app.after_request`) + - Errors (`@app.errorhandler` for 404/500) + +### Example code snippet + +```python +import logging +import json +from datetime import datetime, timezone + +class JSONFormatter(logging.Formatter): + def format(self, record): + log_data = { + "timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "") + "Z", + "level": record.levelname, + "logger": record.name, + "message": record.getMessage(), + } + if record.exc_info: + log_data["exception"] = self.formatException(record.exc_info) + for field in ["endpoint", "method", "status_code", "response_time", "request_id"]: + if hasattr(record, field): + log_data[field] = getattr(record, field) + return json.dumps(log_data) + +handler = logging.StreamHandler() +handler.setFormatter(JSONFormatter()) +logger = logging.getLogger(__name__) +logger.handlers.clear() +logger.addHandler(handler) +logger.setLevel(logging.INFO) +``` + +### Why JSON logging? +- Structured logs are easy to parse and filter in Loki/Grafana. +- Enables LogQL queries by field (e.g., level="ERROR", method="GET"). +- Consistent format for all log events. +- Supports production monitoring and debugging. + +## 5. Dashboard + +### Dashboard Panels + +#### Panel 1: Recent Logs (Logs Panel) + +**LogQL Query**: +``` +{app=~"devops-.*"} +``` + +**Settings**: +- Max lines: 50 +- Show labels: app, container_name +- Sort by: timestamp descending + +**Purpose**: View raw application logs with automatic JSON parsing + +--- + +#### Panel 2: Request Rate (Metric) + +**LogQL Query**: +``` +sum by (app) (rate({app=~"devops-.*"} [1m])) +``` + +**Settings**: +- Graph type: Time series +- Legend: {{endpoint}} +- Y-axis label: requests/sec + +**Purpose**: Monitor HTTP request throughput per endpoint + +--- + +#### Panel 3: Error Logs (Logs Panel) + +**LogQL Query**: +``` +{app=~"devops-.*"} | json | level="ERROR" +``` + +**Settings**: +- Max lines: 100 +- Highlight keywords: ERROR, exception +- Unique: enabled + +**Purpose**: Quick access to error messages and exceptions + +--- + +#### Panel 4: Log Level Distribution (Stat) + +**LogQL Query**: +``` +sum by (level) (count_over_time({app=~"devops-.*"} | json [5m])) +``` + +**Settings**: +- Display: Pie chart +- Unit: short +- Color mode: Value + +**Purpose**: Show distribution of log severity levels + +--- + +### Accessing Grafana + +1. **Open browser**: http://localhost:3000 +2. **Login**: + - Username: `admin` + - Password: (from .env file) +3. **Add Loki datasource**: + - Settings → Data Sources → Add data source + - Select Loki + - URL: `http://loki:3100` + - Save & test +4. **Import dashboard**: + - Create new dashboard + - Add 4 panels as described above + - Set appropriate refresh intervals (5s for logs, 30s for metrics) + +--- + ## Task 2 — Integrate Your Applications + +**JSON log output from your app:** +![json](./screenshots/app_json_task2.png) + +**Grafana showing logs from both applications:** +![logs](./screenshots/grafana_logs_task2.png) + +**Only warning logs:** +![warning](./screenshots/warning_logs_task2.png) + +**Only info logs:** +![info](./screenshots/info_logs_task2.png) + +**With error word:** +![error](./screenshots/error_task2.png) + +## Task 3 — Build Log Dashboard +![dashbord](./screenshots/dashbord_task3.png) + +## 6. Production Configuration + +### Resource Limits (docker-compose.yml) + +```yaml +services: + loki: + image: grafana/loki:${LOKI_VERSION} + deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + reservations: + cpus: '0.5' + memory: 512M + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:3100/ready"] + interval: 10s + timeout: 10s + retries: 5 + start_period: 30s + + promtail: + image: grafana/promtail:${PROMTAIL_VERSION} + deploy: + resources: + limits: + cpus: '0.5' + memory: 512M + reservations: + cpus: '0.25' + memory: 256M + + grafana: + image: grafana/grafana:${GRAFANA_VERSION} + environment: + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD} + GF_SECURITY_DISABLE_BRUTE_FORCE_LOGIN_PROTECTION: 'false' + GF_USERS_ALLOW_SIGN_UP: 'false' + deploy: + resources: + limits: + cpus: '0.5' + memory: 256M +``` + +### Security Measures + +- **Grafana authentication:** Anonymous access disabled, admin password set via `.env` and environment variables. +- **Sensitive data:** `.env` file is gitignored, secrets never committed. +- **Network isolation:** All services run on a dedicated Docker bridge network (`logging`), restricting access. +- **Promtail Docker socket:** Mounted read-only (`:ro`) for least privilege. +- **Health checks:** All services have health checks to ensure availability and auto-restart if unhealthy. +- **Resource limits:** CPU and memory limits set for each service to prevent resource exhaustion. + + +### Retention Policy +- **Loki retention:** Configured to keep logs for 7 days (retention_period: 168h). +- **Why:** Balances troubleshooting needs and disk usage; old logs are automatically deleted. +- **Persistent volumes:** Loki and Grafana use named Docker volumes (loki-data, grafana-data) to ensure data survives container restarts. + +## Task 4 — Production Readiness + + +**`docker-compose ps` showing all services healthy:** +![services](./screenshots/service_healthy_task4.png) + +**Screenshot of Grafana login page (no anonymous access):** +![curl](./screenshots/grafana_login_curl_task4.png) +![page](./screenshots/login_page_task4.png) + + +## 7. Testing + +### 1. Service Health Check + +```bash +docker compose ps +``` + +Expected: All services show "Up (healthy)" + +### 2. Generate Test Logs + +```bash +# Generate HTTP traffic +for i in {1..100}; do + curl -s http://localhost:8000/ > /dev/null + curl -s http://localhost:8000/health > /dev/null + sleep 0.5 +done +``` + +### 3. Query Logs via Grafana + +``` +1. Navigate to Explore +2. Select Loki datasource +3. Query: {job="docker"} | json +4. Verify logs appear with parsed JSON fields +``` + +### 4. Check LogQL Patterns + +```logql +# Count logs by level +sum by (level) (count_over_time({job="docker"} | json [5m])) + +# Find errors +{job="docker"} | json | level="ERROR" | error != "" + +# Request rate by endpoint +rate({job="docker"} | json | endpoint != "" [5m]) + +# Long requests (>100ms) +{job="docker"} | json | duration > 100 +``` + +### 5. Validate Persistence + +```bash +# Stop services +docker compose down + +# Check volumes still exist +docker volume ls | grep loki + +# Restart services +docker compose up -d + +# Verify old logs are still queryable +``` + +## 8. Challenges + +### Loki Ring Module Errors +**Problem:** Loki startup failed with errors about Consul connection. +**Solution:** Changed ring configuration to use `kvstore: store: inmemory` instead of Consul, as recommended for single-node setups. + + + diff --git a/monitoring/docs/LAB08.md b/monitoring/docs/LAB08.md new file mode 100644 index 0000000000..2aba525cb8 --- /dev/null +++ b/monitoring/docs/LAB08.md @@ -0,0 +1,499 @@ +# Lab 8 — Metrics & Monitoring with Prometheus + +## 1. Architecture + +```text + metrics (/metrics) ++-------------------+ ------------------------------> +------------------------+ +| app-python :5000 | | Prometheus :9090 | +| Flask + RED | <------------------------------ | scrape interval: 15s | +| business metrics | PromQL queries | retention: 15d / 10GB | ++-------------------+ +-----------+------------+ + | + | queries / datasource + v + +------------------------+ + | Grafana :3000 | + | Prometheus dashboard | + | login required | + +------------------------+ + ++-------------------+ container logs +-------------------+ push +-------------------+ +| app-python/app-go | -----------------------> | Promtail :9080 | -------------> | Loki :3100 | ++-------------------+ +-------------------+ +-------------------+ +``` + +## 2. Application Instrumentation + +### Metrics Implemented + +| Metric | Type | Purpose | Labels | Why? | +|--------|------|---------|--------|------| +| `http_requests_total` | Counter | Total HTTP requests received | method, endpoint, status | RED method: Rate | +| `http_request_duration_seconds` | Histogram | Request latency distribution | method, endpoint | RED method: Duration | +| `http_requests_in_progress` | Gauge | Active concurrent requests | - | Resource usage monitoring | +| `devops_info_endpoint_calls` | Counter | Endpoint-specific call count | endpoint | Business metric tracking | +| `devops_info_system_collection_seconds` | Histogram | System info collection time | - | Performance monitoring | + +### Implementation Details + +**Location:** `app_python/app.py` + +**Key Code Sections:** + +```python +# Prometheus Metrics Definition +http_requests_total = Counter( + 'http_requests_total', + 'Total HTTP requests', + ['method', 'endpoint', 'status'] +) + +http_request_duration_seconds = Histogram( + 'http_request_duration_seconds', + 'HTTP request duration in seconds', + ['method', 'endpoint'], + buckets=[0.01, 0.05, 0.1, 0.5, 1.0, 5.0] +) + +http_requests_in_progress = Gauge( + 'http_requests_in_progress', + 'HTTP requests currently being processed' +) + +# Request hooks to track metrics +@app.before_request +def before_request_hook(): + http_requests_in_progress.inc() + request.start_time = time.time() + +@app.after_request +def after_request_hook(response): + duration = time.time() - request.start_time + http_request_duration_seconds.labels( + method=request.method, + endpoint=request.path + ).observe(duration) + + http_requests_total.labels( + method=request.method, + endpoint=request.path, + status=response.status_code + ).inc() + + http_requests_in_progress.dec() + return response + +# Metrics endpoint +@app.route("/metrics") +def metrics(): + return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST) +``` + +**Why These Metrics?** +- **RED Method:** Rate (requests/sec), Errors (5xx rate), Duration (latency) +- **Counter:** Total requests never decrease, perfect for tracking totals +- **Histogram:** Buckets allow percentile calculation (p95, p99 latency) +- **Gauge:** Active requests show current system load +- **Low cardinality labels:** endpoint, method, status are bounded values (no user IDs) + +## 3. Prometheus Configuration + +### File: `monitoring/prometheus/prometheus.yml` + +```yaml +global: + scrape_interval: 15s + evaluation_interval: 15s + +storage: + tsdb: + retention_time: 15d + retention_size: 10GB + +scrape_configs: + - job_name: 'prometheus' + static_configs: + - targets: ['localhost:9090'] + + - job_name: 'app' + static_configs: + - targets: ['app-python:5000'] + metrics_path: '/metrics' + + - job_name: 'loki' + static_configs: + - targets: ['loki:3100'] + metrics_path: '/metrics' + + - job_name: 'grafana' + static_configs: + - targets: ['grafana:3000'] + metrics_path: '/metrics' +``` + +### Configuration Explanation + +| Parameter | Value | Purpose | +|-----------|-------|---------| +| `scrape_interval` | 15s | Prometheus scrapes every 15 seconds | +| `evaluation_interval` | 15s | Alert rules evaluated every 15 seconds | +| `retention_time` | 15d | Keep metrics for 15 days | +| `retention_size` | 10GB | Or when disk reaches 10GB (whichever first) | +| `app-python:5000` | Internal Docker port | Inside Docker network uses internal port, not external 8000 | +| `metrics_path` | /metrics | All services expose metrics at /metrics | + +### Why These Settings? + +- **15s scrape interval:** Balance between granularity and load (standard for Docker apps) +- **15d retention:** Allows trend analysis over 2 weeks without huge storage +- **10GB size limit:** Prevents runaway disk usage in production +- **Internal ports in Docker:** Prometheus is inside Docker network, uses internal service names and ports + +## 4. Dashboard Walkthrough + +### Dashboard: "Application Metrics" (7 panels) + +#### Panel 1: Request Rate (Time Series) +- **Query:** `sum(rate(http_requests_total[5m])) by (endpoint)` +- **Type:** Time series graph +- **Purpose:** Shows requests per second for each endpoint +- **What it means:** + - Flat line = consistent traffic + - Spike = traffic burst + - Drop = reduced usage +- **Example reading:** `/` endpoint at 0.06 requests/sec = 3.6 requests/minute + +#### Panel 2: Error Rate (Time Series) +- **Query:** `sum(rate(http_requests_total{status=~"5.."}[5m]))` +- **Type:** Time series graph +- **Purpose:** Shows 5xx (server) errors per second +- **What it means:** + - Should be near zero in healthy system + - Any spike indicates problems + - Correlate with other metrics to find cause +- **Healthy value:** < 0.01 requests/sec + +#### Panel 3: p95 Latency (Time Series) +- **Query:** `histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))` +- **Type:** Time series graph +- **Purpose:** 95th percentile request duration (slowest 5%) +- **What it means:** + - 95% of requests faster than this + - p95 = 0.05s = 50ms latency + - Better metric than average (resistant to outliers) +- **Healthy value:** < 100ms for web apps + +#### Panel 4: Request Duration Heatmap +- **Query:** `rate(http_request_duration_seconds_bucket[5m])` +- **Type:** Heatmap +- **Purpose:** Distribution of request latencies +- **What it means:** + - Orange = common latency range + - Shows if latency is consistent or variable + - Heatmap reveals patterns average can't show +- **Reading:** Most requests cluster in lower latency range (good) + +#### Panel 5: Active Requests (Gauge) +- **Query:** `http_requests_in_progress` +- **Type:** Gauge (circular dial) +- **Purpose:** Current concurrent requests right now +- **What it means:** + - Gauge = instantaneous snapshot + - High gauge + long request duration = bottleneck + - Spike = burst of traffic +- **Healthy value:** < 10 for single-instance app + +#### Panel 6: Status Code Distribution (Pie Chart) +- **Query:** `sum by (status) (rate(http_requests_total[5m]))` +- **Type:** Pie chart +- **Purpose:** Breakdown of 2xx, 4xx, 5xx responses +- **What it means:** + - Green (2xx) = successful responses + - Yellow (4xx) = client errors (missing pages, bad requests) + - Red (5xx) = server errors (should be rare) +- **Healthy ratio:** 95%+ 2xx, <1% 4xx, ~0% 5xx + +#### Panel 7: Uptime (Stat) +- **Query:** `up{job="app"}` +- **Type:** Stat (big number display) +- **Purpose:** Service health status +- **What it means:** + - `1` = UP (green) + - `0` = DOWN (red) + - Shows if service is reachable +- **Healthy value:** Always 1 + +## 5. PromQL Examples & Explanations + +### Basic Queries + +#### 1. Request Rate (per second) +```promql +rate(http_requests_total[5m]) +``` +- **Breakdown:** + - `http_requests_total` = counter (always increasing) + - `[5m]` = look at last 5 minutes of data + - `rate()` = calculate per-second increase +- **Example output:** 0.06 = 3.6 requests/minute +- **When to use:** Understand traffic volume + +#### 2. Error Rate (percentage) +```promql +sum(rate(http_requests_total{status=~"5.."}[5m])) + / +sum(rate(http_requests_total[5m])) * 100 +``` +- **Breakdown:** + - `status=~"5.."` = regex match: 500, 501, 502, etc. + - First sum = 5xx errors per second + - Second sum = all requests per second + - `/` = divide, `*100` = convert to percentage +- **Example output:** 0.5% = 1 error per 200 requests +- **When to use:** Monitor application reliability + +#### 3. P95 Latency (95th percentile) +```promql +histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) +``` +- **Breakdown:** + - `http_request_duration_seconds_bucket` = histogram buckets + - `rate()` = rate of requests in each bucket + - `histogram_quantile(0.95, ...)` = find value where 95% of requests are faster +- **Example output:** 0.05 = 50 milliseconds +- **When to use:** Understand user experience (not affected by one slow outlier) + +#### 4. Average Latency (for comparison) +```promql +rate(http_request_duration_seconds_sum[5m]) + / +rate(http_request_duration_seconds_count[5m]) +``` +- **Breakdown:** + - Histogram provides `_sum` (total time) and `_count` (request count) + - Divide sum by count = average +- **Why p95 > average:** Outliers pull up average +- **When to use:** For reference, p95 is better metric + +#### 5. Requests by Endpoint +```promql +sum by (endpoint) (rate(http_requests_total[5m])) +``` +- **Breakdown:** + - `sum` = aggregate across all label values + - `by (endpoint)` = group by endpoint label + - Groups requests from different methods/statuses +- **Example output:** + ``` + {endpoint="/"} = 0.05 + {endpoint="/health"} = 0.01 + {endpoint="/metrics"} = 0.0002 + ``` +- **When to use:** Find which endpoints are most used + +#### 6. Requests by Method +```promql +sum by (method) (rate(http_requests_total[5m])) +``` +- **Breakdown:** + - Same `sum by` pattern but group by HTTP method +- **Example output:** + ``` + {method="GET"} = 0.06 + {method="POST"} = 0.001 + ``` +- **When to use:** Understand API usage patterns + +## 6. Production Setup + +### Health Checks + +All services have health checks in `docker-compose.yml`: + +**How it works:** +- Every 10 seconds, Docker runs health check +- If it fails 5 times in a row, container marked unhealthy +- Docker can auto-restart unhealthy containers +- Prometheus won't scrape unhealthy targets + +### Resource Limits + +```yaml +prometheus: + deploy: + resources: + limits: + cpus: '1.0' # Max 1 CPU core + memory: 1G # Max 1GB RAM + reservations: + cpus: '0.5' # Guaranteed 0.5 CPU + memory: 512M # Guaranteed 512MB RAM +``` + +**Why limits matter:** +- **Limits:** Prevent runaway resource usage +- **Reservations:** Ensure minimum resources available +- **Prometheus:** Needs 1GB for 15d retention at 1000 series/sec +- **Scaling:** If needs exceed limit, container stops + +### Data Retention + +```yaml +command: + - '--config.file=/etc/prometheus/prometheus.yml' + - '--storage.tsdb.retention.time=15d' + - '--storage.tsdb.retention.size=10GB' +``` + +**Retention Strategy:** +- **15 days:** Allows trend analysis, not too old +- **10GB limit:** Fits in typical Docker volume +- **Whichever comes first:** If 10GB fills before 15d, older data deleted +- **Trade-off:** More data = slower queries, less data = less history + +### Persistent Volumes + +```yaml +volumes: + prometheus-data: + driver: local +``` + +**Why persistence matters:** +- Data survives container restart +- Dashboards don't disappear after crash +- Historical data available after redeployment +- Dashboard (in Grafana volume) survives + +### Network Security + +```yaml +networks: + logging: + driver: bridge +``` + +**Security benefits:** +- All services on isolated Docker bridge network +- Not exposed to host unless port published +- Services can reach each other by name (DNS) +- `prometheus` service can reach `app-python:5000` internally +- Only Prometheus port 9090 exposed to host for Grafana + +## 7. Testing Results +**Task 1:** +- Screenshot of /metrics endpoint output +![](./screenshots/metrics_task1.png) +![](./screenshots/metrics2_task1.png) + +- Code showing metric definitions +![](./screenshots/code_task1.png) + +**Task 2:** +- Screenshot of /targets page showing all targets UP +![](./screenshots/targets_task2.png) + +- Screenshot of a successful PromQL query +![](./screenshots/query_task2.png) + +**Task 3:** +- Screenshot of your custom application dashboard with live data +![](./screenshots/dashboard_task3.png) +- Exported dashboard JSON file (located at `monitoring/dashboard/application_metrics_lab8.json`) + +**Task 4:** +- `docker compose ps` showing all services healthy +![](./screenshots/healthy_task4.png) + +- Proof of data persistence after restart +![](./screenshots/persistence_task4.png) +![](./screenshots/persistence_dashboard_task4.png) + + +## 8. Challenges & Solutions + +### Challenge 1: App target showing 404 NOT FOUND + +**Problem:** Prometheus tried `app-python:8000/metrics` instead of `app-python:5000/metrics` + +**Root cause:** Port mismapping - 8000 is external port, 5000 is internal Docker port + +**Solution:** Changed prometheus.yml to use internal port: +```yaml +targets: ['app-python:5000'] # Internal Docker port +``` + +**Lesson:** Inside Docker networks, use service names and internal ports. External port 8000 is only for host access. + +### Challenge 2: Metrics not appearing in app + +**Problem:** `/metrics` endpoint returned 404 even though code was added + +**Root cause:** Old Docker image being used - needed to rebuild + +**Solution:** +```bash +docker build -t sunflye/devops-info-service:latest app_python/ +docker compose down +docker compose up -d --force-recreate app-python +``` + +**Lesson:** Docker images are cached. Always rebuild after code changes. + + +## 9. Integration with Lab 7 (Loki + Logs) + +### How Metrics and Logs Work Together + +| Aspect | Logs (Lab 7 - Loki) | Metrics (Lab 8 - Prometheus) | +|--------|---------------------|------------------------------| +| **Data type** | Raw event text | Time-series numbers | +| **Storage** | High volume (Loki TSDB) | Compressed (Prometheus TSDB) | +| **Retention** | 7 days | 15 days | +| **Query** | LogQL (text/JSON search) | PromQL (math/aggregation) | +| **Use case** | "What happened at 3pm?" | "How many requests at 3pm?" | +| **Example** | `{"level": "ERROR", "msg": "..."}` | `http_requests_total = 1234` | + +**Working Together:** +1. **Metrics alert** → "Error rate spiked to 5%" +2. **Go to Grafana** → Look at Loki dashboard +3. **LogQL query** → `{app="app-python"} |= "ERROR"` +4. **Root cause found** → "Database connection timeout" + +### Complete Observability Stack + +``` +┌─────────────────────────────────┐ +│ Application Code │ +│ (app_python/app.py) │ +└────────┬────────────────────────┘ + │ + ┌────┴────────────────────┐ + │ │ +┌───▼─────────┐ ┌──────▼──────┐ +│ Logs │ │ Metrics │ +│ (JSON) │ │ (numbers) │ +│ │ │ │ +└────┬────────┘ └──────┬──────┘ + │ │ +┌────▼────────┐ ┌──────▼──────┐ +│ Promtail │ │ Prometheus │ +│ (collects) │ │ (scrapes) │ +└────┬────────┘ └──────┬──────┘ + │ │ +┌────▼────────┐ ┌──────▼──────┐ +│ Loki │ │ Prometheus │ +│ (stores) │ │ (stores) │ +└────┬────────┘ └──────┬──────┘ + │ │ + └──────────┬───────────┘ + │ + ┌────▼──────┐ + │ Grafana │ + │ (unified) │ + └───────────┘ + +Result: Complete visibility into system behavior +``` + diff --git a/monitoring/docs/screenshots/app_json_task2.png b/monitoring/docs/screenshots/app_json_task2.png new file mode 100644 index 0000000000..a48522e339 Binary files /dev/null and b/monitoring/docs/screenshots/app_json_task2.png differ diff --git a/monitoring/docs/screenshots/code_task1.png b/monitoring/docs/screenshots/code_task1.png new file mode 100644 index 0000000000..8a07aa51e8 Binary files /dev/null and b/monitoring/docs/screenshots/code_task1.png differ diff --git a/monitoring/docs/screenshots/dashboard_task3.png b/monitoring/docs/screenshots/dashboard_task3.png new file mode 100644 index 0000000000..d222ff8e1a Binary files /dev/null and b/monitoring/docs/screenshots/dashboard_task3.png differ diff --git a/monitoring/docs/screenshots/dashbord_task3.png b/monitoring/docs/screenshots/dashbord_task3.png new file mode 100644 index 0000000000..601304bf62 Binary files /dev/null and b/monitoring/docs/screenshots/dashbord_task3.png differ diff --git a/monitoring/docs/screenshots/error_task2.png b/monitoring/docs/screenshots/error_task2.png new file mode 100644 index 0000000000..a7e2db8312 Binary files /dev/null and b/monitoring/docs/screenshots/error_task2.png differ diff --git a/monitoring/docs/screenshots/grafana_login_curl_task4.png b/monitoring/docs/screenshots/grafana_login_curl_task4.png new file mode 100644 index 0000000000..b1dbff957d Binary files /dev/null and b/monitoring/docs/screenshots/grafana_login_curl_task4.png differ diff --git a/monitoring/docs/screenshots/grafana_logs_task1.png b/monitoring/docs/screenshots/grafana_logs_task1.png new file mode 100644 index 0000000000..61c10003ed Binary files /dev/null and b/monitoring/docs/screenshots/grafana_logs_task1.png differ diff --git a/monitoring/docs/screenshots/grafana_logs_task2.png b/monitoring/docs/screenshots/grafana_logs_task2.png new file mode 100644 index 0000000000..07d271c9be Binary files /dev/null and b/monitoring/docs/screenshots/grafana_logs_task2.png differ diff --git a/monitoring/docs/screenshots/healthy_task4.png b/monitoring/docs/screenshots/healthy_task4.png new file mode 100644 index 0000000000..3018c43443 Binary files /dev/null and b/monitoring/docs/screenshots/healthy_task4.png differ diff --git a/monitoring/docs/screenshots/info_logs_task2.png b/monitoring/docs/screenshots/info_logs_task2.png new file mode 100644 index 0000000000..2ba52081c6 Binary files /dev/null and b/monitoring/docs/screenshots/info_logs_task2.png differ diff --git a/monitoring/docs/screenshots/login_page_task4.png b/monitoring/docs/screenshots/login_page_task4.png new file mode 100644 index 0000000000..43f46db752 Binary files /dev/null and b/monitoring/docs/screenshots/login_page_task4.png differ diff --git a/monitoring/docs/screenshots/metrics2_task1.png b/monitoring/docs/screenshots/metrics2_task1.png new file mode 100644 index 0000000000..1614ffea45 Binary files /dev/null and b/monitoring/docs/screenshots/metrics2_task1.png differ diff --git a/monitoring/docs/screenshots/metrics_task1.png b/monitoring/docs/screenshots/metrics_task1.png new file mode 100644 index 0000000000..c87f0c9359 Binary files /dev/null and b/monitoring/docs/screenshots/metrics_task1.png differ diff --git a/monitoring/docs/screenshots/persistence_dashboard_task4.png b/monitoring/docs/screenshots/persistence_dashboard_task4.png new file mode 100644 index 0000000000..a3da5110bc Binary files /dev/null and b/monitoring/docs/screenshots/persistence_dashboard_task4.png differ diff --git a/monitoring/docs/screenshots/persistence_task4.png b/monitoring/docs/screenshots/persistence_task4.png new file mode 100644 index 0000000000..6c3104453f Binary files /dev/null and b/monitoring/docs/screenshots/persistence_task4.png differ diff --git a/monitoring/docs/screenshots/query_task2.png b/monitoring/docs/screenshots/query_task2.png new file mode 100644 index 0000000000..08d0564bf7 Binary files /dev/null and b/monitoring/docs/screenshots/query_task2.png differ diff --git a/monitoring/docs/screenshots/service_healthy_task4.png b/monitoring/docs/screenshots/service_healthy_task4.png new file mode 100644 index 0000000000..d96df7fcc8 Binary files /dev/null and b/monitoring/docs/screenshots/service_healthy_task4.png differ diff --git a/monitoring/docs/screenshots/targets_task2.png b/monitoring/docs/screenshots/targets_task2.png new file mode 100644 index 0000000000..18f69c113f Binary files /dev/null and b/monitoring/docs/screenshots/targets_task2.png differ diff --git a/monitoring/docs/screenshots/warning_logs_task2.png b/monitoring/docs/screenshots/warning_logs_task2.png new file mode 100644 index 0000000000..bb56b43765 Binary files /dev/null and b/monitoring/docs/screenshots/warning_logs_task2.png differ diff --git a/monitoring/loki/config.yml b/monitoring/loki/config.yml new file mode 100644 index 0000000000..34e4ba514c --- /dev/null +++ b/monitoring/loki/config.yml @@ -0,0 +1,34 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + log_level: info + +ingester: + chunk_idle_period: 3m + chunk_retain_period: 1m + max_chunk_age: 1h + +limits_config: + retention_period: 168h + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +common: + path_prefix: /loki + replication_factor: 1 + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + ring: + kvstore: + store: inmemory \ No newline at end of file diff --git a/monitoring/prometheus/prometheus.yml b/monitoring/prometheus/prometheus.yml new file mode 100644 index 0000000000..e158ca72e8 --- /dev/null +++ b/monitoring/prometheus/prometheus.yml @@ -0,0 +1,23 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + +scrape_configs: + - job_name: 'prometheus' + static_configs: + - targets: ['localhost:9090'] + + - job_name: 'app' + static_configs: + - targets: ['app-python:5000'] + metrics_path: '/metrics' + + - job_name: 'loki' + static_configs: + - targets: ['loki:3100'] + metrics_path: '/metrics' + + - job_name: 'grafana' + static_configs: + - targets: ['grafana:3000'] + metrics_path: '/metrics' \ No newline at end of file diff --git a/monitoring/promtail/config.yml b/monitoring/promtail/config.yml new file mode 100644 index 0000000000..9d64ab9345 --- /dev/null +++ b/monitoring/promtail/config.yml @@ -0,0 +1,36 @@ +server: + http_listen_port: 9080 + +positions: + filename: /tmp/positions.yaml + +clients: + - url: http://loki:3100/loki/api/v1/push + +scrape_configs: + - job_name: docker + docker_sd_configs: + - host: unix:///var/run/docker.sock + refresh_interval: 5s + relabel_configs: + - source_labels: ['__meta_docker_container_name'] + regex: '/(.*)' + target_label: 'container' + + - source_labels: ['__meta_docker_container_label_app'] + regex: '(.*)' + target_label: 'app' + + - source_labels: ['__meta_docker_container_name'] + regex: '/(.*)' + target_label: 'app' + replacement: 'devops-python' + + - source_labels: ['__meta_docker_container_image_name'] + regex: '(.*):.*' + target_label: 'image' + + - source_labels: ['__meta_docker_container_name'] + regex: '/(.*)' + target_label: 'job' + replacement: 'docker' \ No newline at end of file diff --git a/pulumi/.gitignore b/pulumi/.gitignore new file mode 100644 index 0000000000..20dbdd8605 --- /dev/null +++ b/pulumi/.gitignore @@ -0,0 +1,27 @@ +# Pulumi +venv/ +node_modules/ +*.pyc +__pycache__/ +Pulumi.*.yaml +.pulumi/ + +# Secrets & Keys +*.pem +*.key +*.pub +labsuser.pem +vockey.pem +authorized_key.json +credentials +terraform.tfvars + +# State files +*.tfstate +*.tfstate.* +.terraform/ + +# IDE +.idea/ +*.swp +.vscode/ \ No newline at end of file diff --git a/pulumi/Pulumi.yaml b/pulumi/Pulumi.yaml new file mode 100644 index 0000000000..46f86a6b44 --- /dev/null +++ b/pulumi/Pulumi.yaml @@ -0,0 +1,11 @@ +name: devops-lab04 +description: lab4 +runtime: + name: python + options: + toolchain: pip + virtualenv: venv +config: + pulumi:tags: + value: + pulumi:template: aws-python diff --git a/pulumi/README.md b/pulumi/README.md new file mode 100644 index 0000000000..7b0b6d100b --- /dev/null +++ b/pulumi/README.md @@ -0,0 +1,92 @@ + # AWS Python S3 Bucket Pulumi Template + + A minimal Pulumi template for provisioning a single AWS S3 bucket using Python. + + ## Overview + + This template provisions an S3 bucket (`pulumi_aws.s3.BucketV2`) in your AWS account and exports its ID as an output. It’s an ideal starting point when: + - You want to learn Pulumi with AWS in Python. + - You need a barebones S3 bucket deployment to build upon. + - You prefer a minimal template without extra dependencies. + + ## Prerequisites + + - An AWS account with permissions to create S3 buckets. + - AWS credentials configured in your environment (for example via AWS CLI or environment variables). + - Python 3.6 or later installed. + - Pulumi CLI already installed and logged in. + + ## Getting Started + + 1. Generate a new project from this template: + ```bash + pulumi new aws-python + ``` + 2. Follow the prompts to set your project name and AWS region (default: `us-east-1`). + 3. Change into your project directory: + ```bash + cd + ``` + 4. Preview the planned changes: + ```bash + pulumi preview + ``` + 5. Deploy the stack: + ```bash + pulumi up + ``` + 6. Tear down when finished: + ```bash + pulumi destroy + ``` + + ## Project Layout + + After running `pulumi new`, your directory will look like: + ``` + ├── __main__.py # Entry point of the Pulumi program + ├── Pulumi.yaml # Project metadata and template configuration + ├── requirements.txt # Python dependencies + └── Pulumi..yaml # Stack-specific configuration (e.g., Pulumi.dev.yaml) + ``` + + ## Configuration + + This template defines the following config value: + + - `aws:region` (string) + The AWS region to deploy resources into. + Default: `us-east-1` + + View or update configuration with: + ```bash + pulumi config get aws:region + pulumi config set aws:region us-west-2 + ``` + + ## Outputs + + Once deployed, the stack exports: + + - `bucket_name` — the ID of the created S3 bucket. + + Retrieve outputs with: + ```bash + pulumi stack output bucket_name + ``` + + ## Next Steps + + - Customize `__main__.py` to add or configure additional resources. + - Explore the Pulumi AWS SDK: https://www.pulumi.com/registry/packages/aws/ + - Break your infrastructure into modules for better organization. + - Integrate into CI/CD pipelines for automated deployments. + + ## Help and Community + + If you have questions or need assistance: + - Pulumi Documentation: https://www.pulumi.com/docs/ + - Community Slack: https://slack.pulumi.com/ + - GitHub Issues: https://github.com/pulumi/pulumi/issues + + Contributions and feedback are always welcome! \ No newline at end of file diff --git a/pulumi/__main__.py b/pulumi/__main__.py new file mode 100644 index 0000000000..901cc0701b --- /dev/null +++ b/pulumi/__main__.py @@ -0,0 +1,25 @@ +import pulumi +import pulumi_aws as aws + +key_name = "vockey" + +sg = aws.ec2.SecurityGroup("vm-sg", + description="Allow SSH, HTTP, 5000", + ingress=[ + {"protocol": "tcp", "from_port": 22, "to_port": 22, "cidr_blocks": ["0.0.0.0/0"], "description": "SSH"}, + {"protocol": "tcp", "from_port": 80, "to_port": 80, "cidr_blocks": ["0.0.0.0/0"], "description": "HTTP"}, + {"protocol": "tcp", "from_port": 5000, "to_port": 5000, "cidr_blocks": ["0.0.0.0/0"], "description": "App port"}, + ], + egress=[{"protocol": "-1", "from_port": 0, "to_port": 0, "cidr_blocks": ["0.0.0.0/0"]}] +) + +vm = aws.ec2.Instance("devops-lab-vm", + instance_type="t2.micro", + vpc_security_group_ids=[sg.id], + ami="ami-0b6c6ebed2801a5cb", + key_name=key_name, + tags={"Name": "pulumi-devops-vm"} +) + +pulumi.export('public_ip', vm.public_ip) +pulumi.export('ssh_command', pulumi.Output.concat("ssh -i labsuser.pem ubuntu@", vm.public_ip)) \ No newline at end of file diff --git a/pulumi/requirements.txt b/pulumi/requirements.txt new file mode 100644 index 0000000000..9a1b8d0fb2 --- /dev/null +++ b/pulumi/requirements.txt @@ -0,0 +1,2 @@ +pulumi>=3.0.0,<4.0.0 +pulumi-aws>=7.0.0,<8.0.0 diff --git a/terraform/.gitignore b/terraform/.gitignore new file mode 100644 index 0000000000..3a5bcd3ae5 --- /dev/null +++ b/terraform/.gitignore @@ -0,0 +1,28 @@ +# Terraform state files +*.tfstate +*.tfstate.* +.terraform/ +.terraform.lock.hcl + +# Terraform variable files with secrets +terraform.tfvars +*.tfvars +*.tfvars.json + +# Cloud credentials +labsuser.pem +*.pem +*.key + +# IDE +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log \ No newline at end of file diff --git a/terraform/main.tf b/terraform/main.tf new file mode 100644 index 0000000000..d648c6b78b --- /dev/null +++ b/terraform/main.tf @@ -0,0 +1,50 @@ +provider "aws" { + region = var.region +} + +resource "aws_security_group" "vm_sg" { + name = "vm-sg" + description = "Allow SSH, HTTP, 5000" + ingress { + description = "SSH" + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + ingress { + description = "HTTP" + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + ingress { + description = "Custom App" + from_port = 5000 + to_port = 5000 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } +} + +resource "aws_instance" "vm" { + ami = var.ami_id + instance_type = var.instance_type + security_groups = [aws_security_group.vm_sg.name] + key_name = var.key_name + tags = { + Name = "devops-lab-vm" + } +} + +output "public_ip" { + description = "Public IP" + value = aws_instance.vm.public_ip +} \ No newline at end of file diff --git a/terraform/output.tf b/terraform/output.tf new file mode 100644 index 0000000000..ecaee256d1 --- /dev/null +++ b/terraform/output.tf @@ -0,0 +1,4 @@ +output "ssh_command" { + value = "ssh ubuntu@${aws_instance.vm.public_ip}" + description = "SSH command" +} \ No newline at end of file diff --git a/terraform/variables.tf b/terraform/variables.tf new file mode 100644 index 0000000000..6316a2e915 --- /dev/null +++ b/terraform/variables.tf @@ -0,0 +1,20 @@ +variable "region" { + description = "AWS region for the VM" + default = "us-east-1" +} + +variable "instance_type" { + description = "EC2 instance type" + default = "t2.micro" +} + +variable "ami_id" { + description = "AMI ID for Ubuntu 24.04 in us-east-1" + default = "ami-0b6c6ebed2801a5cb" +} + + +variable "key_name" { + description = "Name of your uploaded EC2 keypair" + default = "vockey" +} \ No newline at end of file