diff --git a/.github/workflows/ansible-deploy.yml b/.github/workflows/ansible-deploy.yml new file mode 100644 index 0000000000..4ebbdeb6ae --- /dev/null +++ b/.github/workflows/ansible-deploy.yml @@ -0,0 +1,39 @@ +name: Ansible Deployment + +on: + push: + branches: [ main, master, lab06 ] + paths: + - 'ansible/**' + - '.github/workflows/ansible-deploy.yml' + +jobs: + deploy: + runs-on: self-hosted + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install Ansible and dependencies + run: | + sudo apt update + sudo apt install -y ansible python3-docker python3-pip + + - name: Create inventory file for local connection + run: | + cd ansible + echo "[webservers]" > inventory/ci.ini + echo "localhost ansible_connection=local" >> inventory/ci.ini + + - name: Deploy with Ansible + env: + ANSIBLE_VAULT_PASSWORD: ${{ secrets.ANSIBLE_VAULT_PASSWORD }} + run: | + cd ansible + echo "$ANSIBLE_VAULT_PASSWORD" > /tmp/vault_pass + ansible-playbook -i inventory/ci.ini playbooks/deploy.yml --vault-password-file /tmp/vault_pass + rm /tmp/vault_pass + - name: Verify deployment + run: | + sleep 10 + curl -f http://localhost:8000/health || exit 1 \ 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..e861141a8e --- /dev/null +++ b/.github/workflows/python-ci.yml @@ -0,0 +1,123 @@ +name: Python CI/CD Pipeline + +on: + push: + branches: [ master, lab03 ] + paths: + - 'app_python/**' + - '.github/workflows/python-ci.yml' + pull_request: + branches: [ master ] + paths: + - 'app_python/**' + +env: + REGISTRY: docker.io + IMAGE_NAME: ${{ github.repository_owner }}/devops-info-service + PYTHON_VERSION: '3.13' + +jobs: + code-quality-and-testing: + name: Code Quality & Testing + runs-on: ubuntu-latest + defaults: + run: + working-directory: app_python + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python ${{ env.PYTHON_VERSION }} + uses: actions/setup-python@v5 + with: + python-version: ${{ env.PYTHON_VERSION }} + cache: 'pip' + cache-dependency-path: 'app_python/requirements.txt' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install flake8 black pytest pytest-cov + + - name: Lint with flake8 + run: | + echo "Running flake8 linting..." + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + + - name: Check code formatting with black + run: | + echo "Checking code formatting with black..." + black --check --diff . + + - name: Run unit tests with pytest + run: | + echo "Running unit tests with pytest..." + pytest --cov=app --cov-report=term-missing -v + + - name: Security scan with Snyk + uses: snyk/actions/python@master + continue-on-error: true + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + with: + args: --severity-threshold=high --file=requirements.txt + + docker-build-and-push: + name: Docker Build & Push + runs-on: ubuntu-latest + needs: code-quality-and-testing + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Generate version tags + id: vars + run: | + echo "DATE_TAG=$(date +'%Y.%m.%d')" >> $GITHUB_OUTPUT + echo "SHORT_SHA=${GITHUB_SHA:0:7}" >> $GITHUB_OUTPUT + + COMMIT_COUNT=$(git rev-list --count --since="$(date +'%Y-%m-%d 00:00:00')" HEAD 2>/dev/null || echo "0") + echo "CALVER_TAG=$(date +'%Y.%m').$COMMIT_COUNT" >> $GITHUB_OUTPUT + + - name: Build and push Docker image + uses: docker/build-push-action@v5 + with: + context: ./app_python + push: true + tags: | + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.vars.outputs.DATE_TAG }} + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.vars.outputs.CALVER_TAG }} + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.vars.outputs.DATE_TAG }}-${{ steps.vars.outputs.SHORT_SHA }} + labels: | + org.opencontainers.image.title=DevOps Info Service + org.opencontainers.image.description=DevOps course info service + org.opencontainers.image.version=${{ steps.vars.outputs.CALVER_TAG }} + org.opencontainers.image.created=${{ steps.vars.outputs.DATE_TAG }} + org.opencontainers.image.revision=${{ github.sha }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Verify pushed images + run: | + echo "Docker images pushed with tags:" + echo "- latest" + echo "- ${{ steps.vars.outputs.DATE_TAG }}" + echo "- ${{ steps.vars.outputs.CALVER_TAG }}" + echo "- ${{ steps.vars.outputs.DATE_TAG }}-${{ steps.vars.outputs.SHORT_SHA }}" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 30d74d2584..91fadf9030 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,15 @@ -test \ No newline at end of file +test +!edge-api/test/ +!edge-api/test/** +*.retry +.vault_pass +ansible/inventory/*.pyc +__pycache__/ +.env +*.crt +*.key +*.tgz +*.lock +!labs/lab18/app_python/flake.lock +result +result-* diff --git a/WORKERS.md b/WORKERS.md new file mode 100644 index 0000000000..9616a02427 --- /dev/null +++ b/WORKERS.md @@ -0,0 +1,351 @@ +# Lab 17: Cloudflare Workers Edge Deployment + +## 1. Cloudflare Setup + +### Project + +The Workers project was created with C3 in `edge-api`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ npm create cloudflare@latest -- edge-api --category=hello-world --type=hello-world --lang=ts --no-deploy --git --accept-defaults +... +🎉 SUCCESS Application created successfully! +``` + +The generated project contains: + +- `edge-api/src/index.ts` - Worker source code +- `edge-api/wrangler.jsonc` - Wrangler configuration +- `edge-api/package.json` - npm scripts and dependencies + +Wrangler is installed and authenticated. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ wrangler --version +4.87.0 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler whoami +👋 You are logged in with an OAuth Token, associated with the email gygplay004@gmail.com. +Account Name Account ID +Gygplay004@gmail.com's Account d41171f20bd0c0769bc04320159e9a07 +``` + +### Platform Concepts + +Cloudflare Workers runs code in a serverless runtime on Cloudflare's global network. The deployment is not a Docker container and there are no user-managed VMs. + +The public `workers.dev` URL used for this lab: + +```text +https://edge-api.s3rap1s-devops.workers.dev +``` + +Bindings are used to attach configuration and state to a Worker: + +- plaintext vars for non-sensitive configuration +- secrets for sensitive values +- KV namespaces for persisted key-value state + + +## 2. Worker API + +### Routes + +The Worker implements these HTTP endpoints: + +| Route | Purpose | +|-------|---------| +| `/` | service metadata and route list | +| `/health` | health check | +| `/edge` | Cloudflare edge request metadata | +| `/config` | plaintext vars and secret presence | +| `/counter` | KV-backed persisted visits counter | + +Unknown routes return JSON with HTTP `404`. + +### Local Development + +The Worker was tested locally with Wrangler. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler dev --local --port 8787 +Ready on http://localhost:8787 +``` + +Local health check: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s http://127.0.0.1:8787/health +{"status":"ok","app":"edge-api","timestamp":"2026-05-01T18:23:47.846Z"} +``` + +Local edge metadata: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s http://127.0.0.1:8787/edge +{"app":"edge-api","deployment":{"platform":"cloudflare-workers","environment":"production","workersDev":true},"edge":{"colo":"AMS","country":"DE","city":"Aachen","asn":202147,"httpProtocol":"HTTP/1.1","tlsVersion":"TLSv1.3"},"request":{"method":"GET","path":"/edge","userAgent":"curl/8.19.0"}} +``` + +Local KV counter: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s http://127.0.0.1:8787/counter +{"key":"visits","visits":1,"persistedIn":"Workers KV"} +``` + +### Tests + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ npm test +✓ test/index.spec.ts (2 tests) 20ms +Test Files 1 passed (1) +Tests 2 passed (2) +``` + + +## 3. Configuration, Secrets, and KV + +### Wrangler Configuration + +`edge-api/wrangler.jsonc` configures the Worker: + +```jsonc +{ + "name": "edge-api", + "main": "src/index.ts", + "compatibility_date": "2026-05-01", + "workers_dev": true, + "preview_urls": true, + "observability": { + "enabled": true + }, + "vars": { + "APP_NAME": "edge-api", + "COURSE_NAME": "devops-core", + "ENVIRONMENT": "production" + }, + "kv_namespaces": [ + { + "binding": "SETTINGS", + "id": "d1434a1bf2e5471598ecbcd86fa64596" + } + ], + "secrets": { + "required": [ + "API_TOKEN", + "ADMIN_EMAIL" + ] + } +} +``` + +Plaintext vars are committed because they are not sensitive. Secret values are not committed; they are stored in Cloudflare and injected through `env`. + +### KV Namespace + +The `SETTINGS` namespace was created and bound to the Worker. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler kv namespace create SETTINGS +✨ Success! +"binding": "SETTINGS", +"id": "d1434a1bf2e5471598ecbcd86fa64596" +``` + +Verification: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler kv namespace list +[ + { + "id": "d1434a1bf2e5471598ecbcd86fa64596", + "title": "SETTINGS", + "supports_url_encoding": true + } +] +``` + +### Secrets + +Two secrets were created with Wrangler: + +```bash +wrangler secret put API_TOKEN +wrangler secret put ADMIN_EMAIL +``` + +Only secret names are visible: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler secret list +[ + { + "name": "ADMIN_EMAIL", + "type": "secret_text" + }, + { + "name": "API_TOKEN", + "type": "secret_text" + } +] +``` + +The deployed `/config` endpoint confirms the bindings are present without exposing values: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s https://edge-api.s3rap1s-devops.workers.dev/config +{"app":"edge-api","course":"devops-core","environment":"production","secrets":{"apiTokenConfigured":true,"adminEmailConfigured":true,"adminEmailDomain":"gmail.com"},"note":"Plaintext vars are safe for non-sensitive values only. Secrets are injected by Wrangler and are not committed."} +``` + + +## 4. Deployment + +The Worker was deployed to `workers.dev`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler deploy +Uploaded edge-api (11.67 sec) +Deployed edge-api triggers (5.94 sec) + https://edge-api.s3rap1s-devops.workers.dev +Current Version ID: 2f7e48ae-a604-41b1-859f-25b8368c8a06 +``` + +Production health check: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s https://edge-api.s3rap1s-devops.workers.dev/health +{"status":"ok","app":"edge-api","timestamp":"2026-05-01T18:45:35.408Z"} +``` + +Production root endpoint: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s https://edge-api.s3rap1s-devops.workers.dev/ +{"app":"edge-api","course":"devops-core","message":"Hello from Cloudflare Workers edge API","environment":"production","timestamp":"2026-05-01T18:33:41.233Z","durationMs":0,"routes":[{"path":"/","method":"GET","description":"Service metadata"},{"path":"/health","method":"GET","description":"Health check"},{"path":"/edge","method":"GET","description":"Cloudflare edge request metadata"},{"path":"/config","method":"GET","description":"Vars and secret presence"},{"path":"/counter","method":"GET","description":"KV-backed persisted counter"}]} +``` + +### Dashboard Screenshot + +![Worker overview](edge-api/screenshots/cloudflare-worker-overview.png) + + +## 5. Edge Behavior + +The `/edge` endpoint returns metadata from `request.cf`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s https://edge-api.s3rap1s-devops.workers.dev/edge +{"app":"edge-api","deployment":{"platform":"cloudflare-workers","environment":"production","workersDev":true},"edge":{"colo":"AMS","country":"DE","city":"Aachen","asn":202147,"httpProtocol":"HTTP/2","tlsVersion":"TLSv1.3"},"request":{"method":"GET","path":"/edge","userAgent":"curl/8.19.0"}} +``` + +Observed edge fields: + +- `colo`: `AMS` +- `country`: `DE` +- `city`: `Aachen` +- `asn`: `202147` +- `httpProtocol`: `HTTP/2` +- `tlsVersion`: `TLSv1.3` + +Workers are globally distributed by Cloudflare automatically. There is no explicit "deploy to 3 regions" step because Cloudflare routes requests to its edge network and runs the Worker near the request path. This differs from VM or PaaS platforms where regions are selected manually. + +Routing concepts: + +- `workers.dev`: Cloudflare-provided public URL for quick Worker access +- Routes: attach a Worker to paths on an existing Cloudflare-managed zone +- Custom Domains: expose a Worker through a dedicated domain or subdomain + +This lab uses `workers.dev`. + + +## 6. Persistence + +The `/counter` endpoint stores the `visits` key in Workers KV. + +Before redeploy: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s https://edge-api.s3rap1s-devops.workers.dev/counter +{"key":"visits","visits":1,"persistedIn":"Workers KV"} +``` + +After redeploy: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler deploy +Current Version ID: 666caa5e-f195-4305-a268-91cd9f27e856 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab17 λ curl -s https://edge-api.s3rap1s-devops.workers.dev/counter +{"key":"visits","visits":2,"persistedIn":"Workers KV"} +``` + +The value remained available after the Worker was redeployed, confirming that the counter is stored outside the Worker code. + + +## 7. Observability and Operations + +### Logs + +The Worker logs request path and edge location with `console.log()`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler tail --format pretty +Connected to edge-api, waiting for logs... +GET https://edge-api.s3rap1s-devops.workers.dev/edge - Ok @ 5/1/2026, 9:35:08 PM + (log) {"message":"request","path":"/edge","method":"GET","colo":"AMS","country":"DE"} +``` + +### Metrics + +Cloudflare dashboard metrics were checked for the Worker. The metrics page shows production traffic and status over time. + +![Worker metrics](edge-api/screenshots/cloudflare-worker-metrics.png) + +### Deployments + +Several deployments and secret-change versions are visible in deployment history. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/edge-api on lab17 λ wrangler deployments list +Created: 2026-05-01T18:33:06.968Z +Version(s): (100%) ff0e0d1a-6fc0-4178-8a8f-49476e62acc5 + +Created: 2026-05-01T18:34:03.139Z +Version(s): (100%) 666caa5e-f195-4305-a268-91cd9f27e856 + +Created: 2026-05-01T18:45:15.665Z +Version(s): (100%) 2f7e48ae-a604-41b1-859f-25b8368c8a06 +``` + +![Worker deployments](edge-api/screenshots/cloudflare-worker-deployments.png) + +A rollback can be performed with: + +```bash +wrangler rollback +``` + +I did not execute rollback because the latest deployment is the desired final version. In a real incident, the previous known-good version from `wrangler deployments list` would be selected and rolled back through Wrangler or the Cloudflare dashboard. + + +## 8. Kubernetes vs Cloudflare Workers + +| Aspect | Kubernetes | Cloudflare Workers | +|--------|------------|--------------------| +| Setup complexity | Requires cluster, nodes, services, ingress, controllers, storage | Requires account, Wrangler project, and bindings | +| Deployment speed | Slower for small apps because infrastructure is explicit | Fast deploys through `wrangler deploy` | +| Global distribution | Requires multi-cluster, geo routing, or external traffic management | Global edge distribution is built in | +| Cost for small apps | Cluster baseline cost can be high | Good fit for small APIs with low operational overhead | +| State/persistence model | PVCs, databases, StatefulSets, external storage | Bindings such as KV, D1, R2, Durable Objects | +| Control/flexibility | High control over runtime, networking, sidecars, operators | More constrained serverless runtime, no arbitrary container host | +| Best use case | Long-running services, complex platforms, custom networking | Lightweight APIs, request routing, edge logic, low-latency global access | + +Use Kubernetes when the workload needs custom runtime control, long-running containers, service mesh, operators, or complex internal networking. + +Use Cloudflare Workers when the workload is an HTTP API, middleware, edge routing layer, or small globally distributed service that benefits from serverless operations. + +For this lab, Workers is simpler for public global access and deployment. The main constraint is that the Worker is not a Docker host, so the Lab 2 Docker image cannot be deployed directly. diff --git a/ansible/README.md b/ansible/README.md new file mode 100644 index 0000000000..8ec7c40722 --- /dev/null +++ b/ansible/README.md @@ -0,0 +1 @@ +[![Ansible Deployment](https://github.com/s3rap1s/DevOps-Core-Course/actions/workflows/ansible-deploy.yml/badge.svg)](https://github.com/s3rap1s/DevOps-Core-Course/actions/workflows/ansible-deploy.yml) \ No newline at end of file diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg new file mode 100644 index 0000000000..7d3d2ea046 --- /dev/null +++ b/ansible/ansible.cfg @@ -0,0 +1,11 @@ +[defaults] +inventory = inventory/hosts.ini +roles_path = roles +host_key_checking = False +remote_user = devops +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..d1ca7ca7ef --- /dev/null +++ b/ansible/docs/LAB05.md @@ -0,0 +1,439 @@ +# Lab 5 — Ansible Fundamentals + +## 1. Architecture Overview + +- **Ansible version**: 2.20.2 (control node: Arch Linux) +- **Target VM**: Ubuntu 24.04 LTS (running on VirtualBox, accessible via SSH on port 2222) +- **Project structure**: Role-based, following recommended Ansible practices. + +``` +ansible +├── ansible.cfg +├── docs +│ └── LAB05.md # this doc +├── inventory +│ ├── group_vars +│ │ └── all.yml # encrypted variables (Ansible vault) +│ └── hosts.ini # static inventory +├── playbooks +│ ├── deploy.yml # application deployment +│ └── provision.yml # system provisioning +└── roles + ├── app_deploy # application deployment + │ ├── defaults + │ │ └── main.yml + │ ├── handlers + │ │ └── main.yml + │ └── tasks + │ └── main.yml + ├── common # common system packages + │ ├── defaults + │ │ └── main.yml + │ ├── handlers + │ └── tasks + │ └── main.yml + └── docker # docker installation + ├── defaults + │ └── main.yml + ├── handlers + │ └── main.yml + └── tasks + └── main.yml +``` + +- **Why roles?** Roles enable modular, reusable, and maintainable automation. Each role focuses on a specific concern, making the playbooks clean and easy to extend. + +## 2. Roles Documentation + +### 2.1 `common` Role + +**Purpose**: Install essential system packages and ensure the system is up‑to‑date. + +**Variables** (in `defaults/main.yml`): +```yaml +common_packages: + - python3-pip + - curl + - wget + - git + - vim + - htop + - net-tools + - unzip +``` + +**Tasks**: +- Update APT cache (with `cache_valid_time=3600` to avoid unnecessary updates) +- Install the packages listed above. + +### 2.2 `docker` Role + +**Purpose**: Install Docker CE and its dependencies, start the Docker service, and add the remote user to the `docker` group. + +**Variables** (`defaults/main.yml`): +```yaml +docker_user: "{{ ansible_user }}" +docker_packages: + - docker-ce + - docker-ce-cli + - containerd.io + - docker-buildx-plugin + - docker-compose-plugin +``` + +**Handlers** (`handlers/main.yml`): +- `restart docker` – restarts the Docker daemon (used after configuration changes). + +**Tasks**: +1. Remove any conflicting packages (like `docker.io`). +2. Install required system packages (`ca-certificates`, `curl`). +3. Create the keyrings directory. +4. Add Docker’s official GPG key. +5. Add the Docker APT repository (using `ansible_distribution_release` to get the Ubuntu codename). +6. Install Docker packages. +7. Ensure Docker is running and enabled. +8. Add the user to the `docker` group. +9. Install `python3-docker` via APT (required for Ansible Docker modules). + +### 2.3 `app_deploy` Role + +**Purpose**: Pull the Docker image from Docker Hub and run the container with the correct configuration. + +**Variables** (`defaults/main.yml`): +```yaml +app_restart_policy: unless-stopped +app_env_vars: {} +``` +Actual values (image name, tag, port) are taken from the encrypted `group_vars/all.yml`. + +**Handlers** (`handlers/main.yml`): +- `restart app container` – restarts the application container (not used in current version but defined for future use). + +**Tasks**: +1. **Login to Docker Hub** – uses credentials from vault (with `no_log: true` to hide secrets). +2. **Pull the Docker image** – pulls `s3rap1s/devops-info-service:latest`. +3. **Check if container is already running** – registers `container_info`. +4. **Stop and remove existing container** – if it exists. +5. **Run the container** – with the following parameters: + - name: `devops-info-service` + - image: `s3rap1s/devops-info-service:latest` + - restart policy: `unless-stopped` + - port mapping: `5000:5000` +6. **Wait for the application to be ready** – using `wait_for` on port 5000. +7. **Verify health endpoint** – using `uri` module to check `/health` returns 200 OK. +8. **Display health check result** – prints the JSON response. + +## 3. Idempotency Demonstration + +### First run of `provision.yml` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab04 ● ● λ ansible-playbook playbooks/provision.yml --vault-password-file .vault_pass + +PLAY [Provision web servers with common tools and Docker] ********************************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] ********************************************************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [common : Update apt cache] *********************************************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [common : Install common essential packages] ****************************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************************************************************ +ok: [devops-vm] + +TASK [docker : Install required system packages] ******************************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] ************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker's official GPG key] ********************************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [docker : Add Docker APT repository] ************************************************************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:39:11 + +37 - name: Add Docker APT repository +38 apt_repository: +39 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker.asc... + ^ column 11 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +changed: [devops-vm] + +TASK [docker : Install Docker packages] **************************************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [docker : Ensure Docker service is running and enabled] ******************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Add user to docker group] *************************************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [docker : Install python3-docker for Ansible docker modules] ************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +PLAY RECAP ********************************************************************************************************************************************************************************************************************************************************************* +devops-vm : ok=5 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 + +``` + +### Second run of `provision.yml` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab04 ● ● λ ansible-playbook playbooks/provision.yml --vault-password-file .vault_pass + +PLAY [Provision web servers with common tools and Docker] ********************************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] ********************************************************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [common : Update apt cache] *********************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [common : Install common essential packages] ****************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************************************************************ +ok: [devops-vm] + +TASK [docker : Install required system packages] ******************************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] ************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker's official GPG key] ********************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker APT repository] ************************************************************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:39:11 + +37 - name: Add Docker APT repository +38 apt_repository: +39 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker.asc... + ^ column 11 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +ok: [devops-vm] + +TASK [docker : Install Docker packages] **************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Ensure Docker service is running and enabled] ******************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Add user to docker group] *************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install python3-docker for Ansible docker modules] ************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +PLAY RECAP ********************************************************************************************************************************************************************************************************************************************************************* +devops-vm : ok=12 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +**Analysis**: +- First run: many tasks reported **changed** because packages were installed, repositories added, etc. +- Second run: all tasks reported **ok** (green) because the system already matched the desired state. +- This **idempotency** proves that the roles are correctly written – they only make changes when necessary and do not break anything when run repeatedly. + +## 4. Ansible Vault Usage + +Sensitive information (Docker Hub credentials) is stored encrypted using Ansible Vault. + +**Creation of vault file**: +```bash +ansible-vault create inventory/group_vars/all.yml +``` +Vault password is stored in a local `.vault_pass` file (added to `.gitignore`). The vault file contains: +```yaml +dockerhub_username: "s3rap1s" +dockerhub_password: "dckr_pat_xxxxxx" # nah uh +app_name: "devops-info-service" +docker_image: "{{ dockerhub_username }}/{{ app_name }}" +docker_image_tag: "latest" +app_port: 5000 +app_container_name: "{{ app_name }}" +``` + +**Usage in playbook**: +All tasks that use these variables refer to them normally. The vault password is supplied via the command line: +```bash +ansible-playbook playbooks/deploy.yml --vault-password-file .vault_pass +``` + +**Why Ansible Vault matters**: +- Secrets are never exposed in plain text. +- The vault file can be safely committed to Git (it is encrypted). +- Access to secrets is controlled by the vault password, which is kept outside the repository. + +## 5. Deployment Verification + +### Playbook execution +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab04 ● ● λ ansible-playbook playbooks/deploy.yml --vault-password-file .vault_pass + +PLAY [Deploy application] ****************************************************************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] ********************************************************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [app_deploy : Log in to Docker Hub] *************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [app_deploy : Pull Docker image] ****************************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [app_deploy : Check if container is running] ****************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [app_deploy : Stop and remove existing container if it exists] ************************************************************************************************************************************************************************************************************ +changed: [devops-vm] + +TASK [app_deploy : Run Docker container] *************************************************************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [app_deploy : Wait for application to be ready] *************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [app_deploy : Verify health endpoint] ************************************************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [app_deploy : Display health check result] ******************************************************************************************************************************************************************************************************************************** +ok: [devops-vm] => { + "msg": "Health check passed! Response: {'status': 'healthy', 'timestamp': '2026-02-25T13:03:39.898895+00:00', 'uptime_seconds': 5}" +} + +PLAY RECAP ********************************************************************************************************************************************************************************************************************************************************************* +devops-vm : ok=9 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 + +``` + +### Manual checks +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab04 ● ● λ ssh devops@localhost -p 2222 +Welcome to Ubuntu 24.04.4 LTS (GNU/Linux 6.8.0-100-generic x86_64) + + * Documentation: https://help.ubuntu.com + * Management: https://landscape.canonical.com + * Support: https://ubuntu.com/pro + + System information as of Wed Feb 25 01:03:17 PM UTC 2026 + + System load: 0.0 + Usage of /: 16.8% of 24.44GB + Memory usage: 20% + Swap usage: 0% + Processes: 111 + Users logged in: 1 + IPv4 address for enp0s3: 10.0.2.15 + IPv6 address for enp0s3: fd17:625c:f037:2:a00:27ff:fe00:936e + + * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s + just raised the bar for easy, resilient and secure K8s cluster deployment. + + https://ubuntu.com/engage/secure-kubernetes-at-the-edge + +Expanded Security Maintenance for Applications is not enabled. + +20 updates can be applied immediately. +17 of these updates are standard security updates. +To see these additional updates run: apt list --upgradable + +Enable ESM Apps to receive additional future security updates. +See https://ubuntu.com/esm or run: sudo pro status + + +Last login: Wed Feb 25 13:03:39 2026 from 10.0.2.2 +devops@devops:~$ docker ps +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +9efe64c0a550 s3rap1s/devops-info-service:latest "python app.py" 28 seconds ago Up 27 seconds 0.0.0.0:5000->5000/tcp devops-info-service +devops@devops:~$ curl http://localhost:5000/health +{"status":"healthy","timestamp":"2026-02-25T13:04:18.686599+00:00","uptime_seconds":44} +``` + +Everything works as expected – the application is running and healthy. + +## 6. Key Decisions + +### Why use roles instead of plain playbooks? +- **Reusability**: the same role can be applied to multiple hosts or projects. +- **Maintainability**: each role is isolated, making it easier to update or debug one part without affecting others. +- **Clarity**: the structure clearly separates concerns (system, Docker, application). + +### How do roles improve reusability? +- Roles can be shared via Ansible Galaxy. +- Variables and defaults allow easy customisation without changing the role code. +- Handlers and files are bundled together, so the role is self-contained. + +### What makes a task idempotent? +- Using state‑oriented modules (e.g., `apt: state=present`, `service: state=started`) instead of raw commands. +- Modules check the current state before applying changes and only act when necessary. +- For example, the Docker repository is added only once; subsequent runs see that it already exists. + +### How do handlers improve efficiency? +- Handlers are triggered only when a task reports a change, and run once at the end of the play. +- This avoids unnecessary restarts (e.g., restarting Docker after every small change). + +### Why is Ansible Vault necessary? +- To store secrets (passwords, tokens) securely in version control. +- Prevents accidental exposure of credentials. +- Enforces that only authorised users (with the vault password) can see the secrets. + +## 7. Challenges (Optional) + +- **HashiCorp repository error**: The target VM had a broken `hashicorp.list` file that caused `apt update` to fail. Solved by manually removing the file (`sudo rm /etc/apt/sources.list.d/hashicorp.list`). +- **Python external‑management error**: Ubuntu 24.04 blocks `pip install` system‑wide. Replaced `pip` installation of `docker` Python module with `apt install python3-docker`. +- **Vault variables not visible in roles**: Initially the variables from `group_vars/all.yml` were not loaded because the file was placed in the wrong directory. Moving it to `inventory/group_vars/all.yml` solved the issue. +- **Timeout on health check**: The `wait_for` task was delegated to `localhost` while the container runs inside the VM. Removing `delegate_to: localhost` fixed it. + +## 8. Bonus Task – Dynamic Inventory (Theoretical) + +If I had a cloud VM (e.g., on AWS or Yandex Cloud), I would implement dynamic inventory to avoid hardcoding IP addresses. + +**Planned approach** (for AWS as an example): + +1. Install the required collection: + ```bash + ansible-galaxy collection install amazon.aws + ``` + +2. Create `inventory/aws_ec2.yml`: + ```yaml + plugin: amazon.aws.aws_ec2 + regions: + - us-east-1 + filters: + instance-state-name: running + tag:Environment: dev + keyed_groups: + - key: tags.Role + prefix: role + hostnames: + - public-ip-address + compose: + ansible_user: "'ubuntu'" + ``` + +3. Use it with the existing playbooks: + ```bash + ansible-playbook -i inventory/aws_ec2.yml playbooks/provision.yml + ``` + +**Benefits of dynamic inventory**: +- Automatically discovers new instances. +- Groups hosts by tags (e.g., `role_webserver`). +- No manual updates when IPs change. + +**Why not implemented here**: +- I used a local VM for cost reasons and simplicity, so there is no cloud infrastructure to manage dynamically. diff --git a/ansible/docs/LAB06.md b/ansible/docs/LAB06.md new file mode 100644 index 0000000000..d176abbd3d --- /dev/null +++ b/ansible/docs/LAB06.md @@ -0,0 +1,799 @@ +# Lab 6: Advanced Ansible & CI/CD - Submission + +**Name:** Amirkhan Kurbanov +**Date:** 2026-03-04 +**Lab Points:** 10 + + +## Task 1: Blocks & Tags (2 pts) + +### Implementation +- Refactored the `common` role to use a block for package installation with tags `packages` and an `always` block for logging completion. +- Refactored the `docker` role into two blocks: `docker_install` (installation tasks) and `docker_config` (configuration tasks), each with corresponding tags. Added an `always` block to ensure Docker service is enabled. +- Added tags at role level (`common`, `docker`) and at task/block level for fine‑grained control. + +### Testing Evidence + +#### List all available tags +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/provision.yml --list-tags --vault-password-file .vault_pass + +playbook: playbooks/provision.yml + + play #1 (webservers): Provision web servers with common tools and Docker TAGS: [] + TASK TAGS: [common, docker, docker_config, docker_install, packages] +``` + +#### Run only `common` role +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab05 ● λ ansible-playbook playbooks/provision.yml --tags common --vault-password-file .vault_pass + +PLAY [Provision web servers with common tools and Docker] ************************************************************************************************************************************************************************ + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [common : Update apt cache] ************************************************************************************************************************************************************************************************* +changed: [devops-vm] + +TASK [common : Install common packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [common : Log completion] *************************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/common/tasks/main.yml:29:18 + +27 - name: Log completion +28 copy: +29 content: "Common role completed at {{ ansible_date_time.iso8601 }}" + ^ column 18 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +changed: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +#### Run only `packages` tag (within `common` role) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab05 ● λ ansible-playbook playbooks/provision.yml --tags packages --vault-password-file .vault_pass + +PLAY [Provision web servers with common tools and Docker] ************************************************************************************************************************************************************************ + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [common : Update apt cache] ************************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [common : Install common packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 + +``` + +#### Run only `docker_install` tag +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/provision.yml --tags docker_install --vault-password-file .vault_pass + +PLAY [Provision web servers with common tools and Docker] ************************************************************************************************************************************************************************ + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install required system packages] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] **************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker GPG key] *********************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker APT repository] **************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:41:15 + +39 - name: Add Docker APT repository +40 apt_repository: +41 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker... + ^ column 15 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +ok: [devops-vm] + +TASK [docker : Install Docker packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Ensure Docker service is running] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Ensure Docker enabled after block] ******************************************************************************************************************************************************************************** +ok: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=9 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 + +``` + +#### Run only `docker_config` tag +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/provision.yml --tags docker_config --vault-password-file .vault_pass + +PLAY [Provision web servers with common tools and Docker] ************************************************************************************************************************************************************************ + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add user to docker group] ***************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install python3-docker] ******************************************************************************************************************************************************************************************* +ok: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` + +### Research Answers +- **Q: What happens if rescue block also fails?** + If the rescue block itself fails, the task execution stops and Ansible reports a failure. The `always` block will still run regardless of success or failure of both the main block and the rescue block. +- **Q: Can you have nested blocks?** + Yes, blocks can be nested. Inner blocks inherit the directives (`when`, `become`, `tags`) of outer blocks, and each block can have its own rescue/always sections. +- **Q: How do tags inherit to tasks within blocks?** + Tags applied to a block are automatically applied to all tasks inside that block, unless a task overrides them with its own tags. + + +## Task 2: Upgrade to Docker Compose (3 pts) + +### Implementation +- Renamed `app_deploy` role to `web_app` (`mv app_deploy web_app`). +- Created a Jinja2 template `roles/web_app/templates/docker-compose.yml.j2`: + ```yaml + services: + {{ app_name }}: + image: "{{ docker_image }}:{{ docker_tag }}" + container_name: "{{ app_name }}" + ports: + - "{{ app_port }}:{{ app_internal_port }}" + environment: + - HOST=0.0.0.0 + - PORT={{ app_internal_port }} +{% if app_env_vars is defined and app_env_vars %} +{% for key, value in app_env_vars.items() %} + - {{ key }}={{ value }} +{% endfor %} +{% endif %} + restart: unless-stopped + networks: + - app_network + +networks: + app_network: + driver: bridge + ``` +- Added role dependency in `roles/web_app/meta/main.yml`: + ```yaml + dependencies: + - role: docker + ``` +- Updated `roles/web_app/tasks/main.yml` to create the project directory, template the compose file, and deploy using `community.docker.docker_compose_v2`. +- Configured variables in `group_vars/all.yml` (encrypted with Vault): + ```yaml + app_name: devops-python + docker_image: s3rap1s/devops-info-service + docker_tag: latest + app_port: 8000 + app_internal_port: 8000 + compose_project_dir: "/opt/{{ app_name }}" + ``` + +### Testing Evidence + +#### First deployment (shows changes) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install required system packages] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] **************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker GPG key] *********************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker APT repository] **************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:41:15 + +39 - name: Add Docker APT repository +40 apt_repository: +41 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker... + ^ column 15 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +ok: [devops-vm] + +TASK [docker : Install Docker packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Ensure Docker service is running] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Ensure Docker enabled after block] ******************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add user to docker group] ***************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install python3-docker] ******************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Docker role complete (always)] ************************************************************************************************************************************************************************************ +ok: [devops-vm] => { + "msg": "Docker role finished" +} + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +skipping: [devops-vm] + +TASK [web_app : Ensure project directory exists] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [web_app : Template docker-compose.yml] ************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [web_app : Deploy with docker-compose] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=15 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 +``` + +#### Second run (idempotency – no changes) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install required system packages] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] **************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker GPG key] *********************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker APT repository] **************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:41:15 + +39 - name: Add Docker APT repository +40 apt_repository: +41 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker... + ^ column 15 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +ok: [devops-vm] + +TASK [docker : Install Docker packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Ensure Docker service is running] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Ensure Docker enabled after block] ******************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add user to docker group] ***************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install python3-docker] ******************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Docker role complete (always)] ************************************************************************************************************************************************************************************ +ok: [devops-vm] => { + "msg": "Docker role finished" +} + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +skipping: [devops-vm] + +TASK [web_app : Ensure project directory exists] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [web_app : Template docker-compose.yml] ************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [web_app : Deploy with docker-compose] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=15 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 +``` + +#### Generated docker-compose.yml on target VM +```bash +devops@devops:~$ cat /opt/devops-python/docker-compose.yml +services: + devops-python: + image: "s3rap1s/devops-info-service:latest" + container_name: "devops-python" + ports: + - "8000:8000" + environment: + - HOST=0.0.0.0 + - PORT=8000 + restart: unless-stopped + networks: + - app_network + +networks: + app_network: + driver: bridge +``` + +#### Application is accessible +```bash +devops@devops:~$ curl http://localhost:8000/health +{"status":"healthy","timestamp":"2026-03-04T14:32:32.965187+00:00","uptime_seconds":5351} +``` + +### Research Answers +- **Q: What's the difference between `restart: always` and `restart: unless-stopped`?** + `always` restarts the container regardless of its exit status, even if it was manually stopped. `unless-stopped` restarts unless the container was explicitly stopped by the user. +- **Q: How do Docker Compose networks differ from Docker bridge networks?** + Compose creates a user‑defined bridge network with automatic DNS resolution between containers. It provides better isolation and service discovery than the default bridge. +- **Q: Can you reference Ansible Vault variables in the template?** + Yes, variables decrypted by Ansible Vault can be used directly in templates. The template is rendered after vault decryption. + + +## Task 3: Wipe Logic (1 pt) + +### Implementation +- Added `web_app_wipe` variable (default: `false`) in `roles/web_app/defaults/main.yml`. +- Created `roles/web_app/tasks/wipe.yml` with tasks to stop/remove containers, delete the compose file, and remove the project directory, all inside a block with `when: web_app_wipe | bool` and tag `web_app_wipe`. +- Included `wipe.yml` at the beginning of `roles/web_app/tasks/main.yml` with the same tag. +- The wipe logic runs only when explicitly enabled (`-e "web_app_wipe=true"`) and/or the tag is used. + +### Testing Scenarios + +#### Scenario 1: Normal deployment (wipe should NOT run) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install required system packages] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] **************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker GPG key] *********************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker APT repository] **************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:41:15 + +39 - name: Add Docker APT repository +40 apt_repository: +41 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker... + ^ column 15 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +ok: [devops-vm] + +TASK [docker : Install Docker packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Ensure Docker service is running] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Ensure Docker enabled after block] ******************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add user to docker group] ***************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install python3-docker] ******************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Docker role complete (always)] ************************************************************************************************************************************************************************************ +ok: [devops-vm] => { + "msg": "Docker role finished" +} + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +skipping: [devops-vm] + +TASK [web_app : Ensure project directory exists] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [web_app : Template docker-compose.yml] ************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [web_app : Deploy with docker-compose] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=15 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 +``` + +#### Scenario 2: Wipe only (remove existing deployment) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml -e "web_app_wipe=true" --tags web_app_wipe --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +included: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/web_app/tasks/wipe.yml for devops-vm + +TASK [web_app : Stop and remove containers] ************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [web_app : Remove docker-compose file] ************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [web_app : Remove project directory] **************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [web_app : Log wipe completion] ********************************************************************************************************************************************************************************************* +ok: [devops-vm] => { + "msg": "Application devops-python wiped successfully" +} + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` +After this, the container and directory are gone. + +#### Scenario 3: Clean reinstallation (wipe → deploy) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml -e "web_app_wipe=true" --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Remove conflicting packages] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install required system packages] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Create keyrings directory] **************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker GPG key] *********************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add Docker APT repository] **************************************************************************************************************************************************************************************** +[WARNING]: Deprecation warnings can be disabled by setting `deprecation_warnings=False` in ansible.cfg. +[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24. +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/docker/tasks/main.yml:41:15 + +39 - name: Add Docker APT repository +40 apt_repository: +41 repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker... + ^ column 15 + +Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. + +ok: [devops-vm] + +TASK [docker : Install Docker packages] ****************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Ensure Docker service is running] ********************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Ensure Docker enabled after block] ******************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Add user to docker group] ***************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [docker : Install python3-docker] ******************************************************************************************************************************************************************************************* +ok: [devops-vm] + +TASK [docker : Docker role complete (always)] ************************************************************************************************************************************************************************************ +ok: [devops-vm] => { + "msg": "Docker role finished" +} + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +included: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/web_app/tasks/wipe.yml for devops-vm + +TASK [web_app : Stop and remove containers] ************************************************************************************************************************************************************************************** +[ERROR]: Task failed: Module failed: "/opt/devops-python" is not a directory +Origin: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/web_app/tasks/wipe.yml:3:7 + +1 - name: Wipe application +2 block: +3 - name: Stop and remove containers + ^ column 7 + +fatal: [devops-vm]: FAILED! => {"changed": false, "msg": "\"/opt/devops-python\" is not a directory"} +...ignoring + +TASK [web_app : Remove docker-compose file] ************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [web_app : Remove project directory] **************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [web_app : Log wipe completion] ********************************************************************************************************************************************************************************************* +ok: [devops-vm] => { + "msg": "Application devops-python wiped successfully" +} + +TASK [web_app : Ensure project directory exists] ********************************************************************************************************************************************************************************* +changed: [devops-vm] + +TASK [web_app : Template docker-compose.yml] ************************************************************************************************************************************************************************************* +changed: [devops-vm] + +TASK [web_app : Deploy with docker-compose] ************************************************************************************************************************************************************************************** +changed: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=20 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1 +``` +After completion, the application is running fresh. + +#### Scenario 4a: Safety check – tag specified but variable false +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml --tags web_app_wipe --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +skipping: [devops-vm] + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 +``` +Wipe does not run because `when` condition is false. + +#### Scenario 4b: Variable true, only wipe (deployment skipped) +```bash +s3rap1s in ~/devops/DevOps-Core-Course/ansible on lab06 ● ● λ ansible-playbook playbooks/deploy.yml -e "web_app_wipe=true" --tags web_app_wipe --vault-password-file .vault_pass + +PLAY [Deploy application] ******************************************************************************************************************************************************************************************************** + +TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************** +ok: [devops-vm] + +TASK [web_app : Include wipe tasks] ********************************************************************************************************************************************************************************************** +included: /home/s3rap1s/devops/DevOps-Core-Course/ansible/roles/web_app/tasks/wipe.yml for devops-vm + +TASK [web_app : Stop and remove containers] ************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [web_app : Remove docker-compose file] ************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [web_app : Remove project directory] **************************************************************************************************************************************************************************************** +changed: [devops-vm] + +TASK [web_app : Log wipe completion] ********************************************************************************************************************************************************************************************* +ok: [devops-vm] => { + "msg": "Application devops-python wiped successfully" +} + +PLAY RECAP *********************************************************************************************************************************************************************************************************************** +devops-vm : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +``` +Only wipe runs, no deployment. + +### Research Answers +- **Why use both variable AND tag?** + Double safety: the tag allows selective execution, while the variable ensures that even if the tag is accidentally used, the wipe won't run unless explicitly enabled. +- **What's the difference between `never` tag and this approach?** + The `never` tag prevents tasks from running unless specifically requested. This approach uses a variable for finer control – wipe can be triggered either by the tag alone (if variable is true) or by the variable alone (if tag not used but variable true). +- **Why must wipe logic come BEFORE deployment in main.yml?** + To enable clean reinstallation: wipe removes the old application, then deployment installs a fresh copy. +- **When would you want clean reinstallation vs. rolling update?** + Clean reinstallation is useful when configuration has changed drastically or the application needs a fresh state. Rolling updates are for zero‑downtime upgrades. +- **How would you extend this to wipe Docker images and volumes too?** + Add tasks to prune images (`docker image prune -af`) and remove volumes (`docker volume prune -f`) using Ansible modules. + + +## Task 4: CI/CD with GitHub Actions (3 pts) + +### Implementation +- Set up a self‑hosted runner on the target VM (Ubuntu 24.04) following GitHub instructions. +- Created workflow file `.github/workflows/ansible-deploy.yml` with path filters to trigger only on changes to `ansible/**` and the workflow itself. +- The workflow uses the self‑hosted runner (`runs-on: self-hosted`), installs Ansible and required packages via `apt`, decrypts the vault password from a GitHub secret, runs `deploy.yml`, and verifies the application with `curl`. + +### Workflow File +```yaml +name: Ansible Deployment + +on: + push: + branches: [ main, master, lab06 ] + paths: + - 'ansible/**' + - '.github/workflows/ansible-deploy.yml' + +jobs: + deploy: + runs-on: self-hosted + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install Ansible and dependencies + run: | + sudo apt update + sudo apt install -y ansible python3-docker python3-pip + + - name: Create inventory file for local connection + run: | + cd ansible + echo "[webservers]" > inventory/ci.ini + echo "localhost ansible_connection=local" >> inventory/ci.ini + + - name: Deploy with Ansible + env: + ANSIBLE_VAULT_PASSWORD: ${{ secrets.ANSIBLE_VAULT_PASSWORD }} + run: | + cd ansible + echo "$ANSIBLE_VAULT_PASSWORD" > /tmp/vault_pass + ansible-playbook -i inventory/ci.ini playbooks/deploy.yml --vault-password-file /tmp/vault_pass + rm /tmp/vault_pass + - name: Verify deployment + run: | + sleep 10 + curl -f http://localhost:8000/health || exit 1 +``` + +### GitHub Secret +- `ANSIBLE_VAULT_PASSWORD` – the vault password (stored as a secret). + +### Successful Workflow Log +``` +Current runner version: '2.332.0' +Runner name: '***' +Runner group name: 'Default' +Machine name: '***' +GITHUB_TOKEN Permissions +Secret source: Actions +Prepare workflow directory +Prepare all required actions +Getting action download info +Download action repository 'actions/checkout@v4' (SHA:34e114876b0b11c390a56381ad16ebd13914f8d5) +Complete job name: deploy +1s +2s +Reading package lists... +Building dependency tree... +Reading state information... +7 packages can be upgraded. Run 'apt list --upgradable' to see them. +WARNING: apt does not have a stable CLI interface. Use with caution in scripts. +Reading package lists... +Building dependency tree... +Reading state information... +ansible is already the newest version (9.2.0+dfsg-0ubuntu5). +python3-docker is already the newest version (5.0.3-1ubuntu1.1). +python3-pip is already the newest version (24.0+dfsg-1ubuntu1.3). +0 upgraded, 0 newly installed, 0 to remove and 7 not upgraded. +0s +Run cd ansible + +23s +Run cd ansible + +PLAY [Deploy application] ****************************************************** +TASK [Gathering Facts] ********************************************************* +ok: [localhost] +TASK [app_deploy : Log in to Docker Hub] *************************************** +ok: [localhost] +TASK [app_deploy : Pull Docker image] ****************************************** +ok: [localhost] +TASK [app_deploy : Check if container is running] ****************************** +ok: [localhost] +TASK [app_deploy : Stop and remove existing container if it exists] ************ +changed: [localhost] +TASK [app_deploy : Run Docker container] *************************************** +changed: [localhost] +TASK [app_deploy : Wait for application to be ready] *************************** +ok: [localhost] +TASK [app_deploy : Verify health endpoint] ************************************* +ok: [localhost] +TASK [app_deploy : Display health check result] ******************************** +ok: [localhost] => { + "msg": "Health check passed! Response: {'status': 'healthy', 'timestamp': '2026-03-04T13:54:53.345136+00:00', 'uptime_seconds': 5}" +} +PLAY RECAP ********************************************************************* +localhost : ok=9 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 +10s +Run sleep 10 + + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 +{"status":"healthy","timestamp":"2026-03-04T13:55:03.528080+00:00","uptime_seconds":3102} +100 90 100 90 0 0 9153 0 --:--:-- --:--:-- --:--:-- 10000 +0s +Post job cleanup. +/usr/bin/git version +git version 2.43.0 +Temporarily overriding HOME='/home/***/actions-runner/_work/_temp/099c7d1c-ff33-42f8-aca6-2bfd69c3eac2' before making global git config changes +Adding repository directory to the temporary git global config as a safe directory +/usr/bin/git config --global --add safe.directory /home/***/actions-runner/_work/DevOps-Core-Course/DevOps-Core-Course +/usr/bin/git config --local --name-only --get-regexp core\.sshCommand +/usr/bin/git submodule foreach --recursive sh -c "git config --local --name-only --get-regexp 'core\.sshCommand' && git config --local --unset-all 'core.sshCommand' || :" +/usr/bin/git config --local --name-only --get-regexp http\.https\:\/\/github\.com\/\.extraheader +http.https://github.com/.extraheader +/usr/bin/git config --local --unset-all http.https://github.com/.extraheader +/usr/bin/git submodule foreach --recursive sh -c "git config --local --name-only --get-regexp 'http\.https\:\/\/github\.com\/\.extraheader' && git config --local --unset-all 'http.https://github.com/.extraheader' || :" +/usr/bin/git config --local --name-only --get-regexp ^includeIf\.gitdir: +/usr/bin/git submodule foreach --recursive git config --local --show-origin --name-only --get-regexp remote.origin.url +0s +Cleaning up orphan processes +``` + +### Status Badge +Added to `ansible/README.md`: +```markdown +[![Ansible Deployment](https://github.com/s3rap1s/DevOps-Core-Course/actions/workflows/ansible-deploy.yml/badge.svg)](https://github.com/s3rap1s/DevOps-Core-Course/actions/workflows/ansible-deploy.yml) +``` + +### Research Answers +- **What are the security implications of storing SSH keys in GitHub Secrets?** + Secrets are encrypted and not exposed in logs, but they are still accessible to anyone with write access to the repository. They should be rotated regularly and have minimal permissions. +- **How would you implement a staging → production deployment pipeline?** + Use separate workflows for staging and production, or use environments with approval gates. The staging workflow could deploy to a test VM, run integration tests, and then trigger production deployment after manual approval. +- **What would you add to make rollbacks possible?** + Store previous Docker image tags and have a playbook that redeploys the previous version. In CI/CD, you could keep the last successful image tag and provide a rollback workflow. +- **How does self-hosted runner improve security compared to GitHub-hosted?** + A self‑hosted runner behind your firewall eliminates the need to open SSH ports to the internet and keeps secrets entirely within your infrastructure. diff --git a/ansible/inventory/group_vars/all.yml b/ansible/inventory/group_vars/all.yml new file mode 100644 index 0000000000..bbf95680bf --- /dev/null +++ b/ansible/inventory/group_vars/all.yml @@ -0,0 +1,17 @@ +$ANSIBLE_VAULT;1.1;AES256 +62656339613935316166383364326566333665356338323539303433306563626263363161323765 +3135653937323865353832306531373537633232386366350a326236376231386233353135633834 +63653338303162386338626439653866613838383031653565313038633939613130356564303765 +3035343461376437610a393966343664373064313262646637636533383463623137313665386131 +30393235366330353335623434363538306438313038616639653866356337623763353138666137 +39646430363362663736313266383638333762363235383362646539366337303864353732303334 +30666566303361613034373366643738316537626533643865653034373535383038663866363261 +62386537383835663031393862343831323536353430636639366232626266616137323666376131 +38343634663734363563303538383266646265353534333561633663386233343762623364363064 +37393334336438303962356139346638343161396139613231373533343036636431373336326436 +64643034346533663337313332303661386637616562363366656439313036323137616631303264 +35353837653266373266323738336665333832333533656663343731353533353838663766363836 +39326632353836356139663164323232393064666532633033316662363135626437623762333439 +30633862656132613164393035336336353336313064373032613133616137633838356466306533 +63383139366431343764366532376562313165326431656137636231336433623932616162383831 +33636639306434376432 diff --git a/ansible/inventory/hosts.ini b/ansible/inventory/hosts.ini new file mode 100644 index 0000000000..f84bb682b6 --- /dev/null +++ b/ansible/inventory/hosts.ini @@ -0,0 +1,5 @@ +[webservers] +devops-vm ansible_host=127.0.0.1 ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_ed25519 + +[webservers: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..31d9e5c965 --- /dev/null +++ b/ansible/playbooks/deploy.yml @@ -0,0 +1,6 @@ +- name: Deploy application + hosts: webservers + become: yes + + roles: + - web_app diff --git a/ansible/playbooks/provision.yml b/ansible/playbooks/provision.yml new file mode 100644 index 0000000000..abc6c81307 --- /dev/null +++ b/ansible/playbooks/provision.yml @@ -0,0 +1,7 @@ +- name: Provision web servers with common tools and Docker + hosts: webservers + become: yes + + roles: + - common + - docker \ No newline at end of file diff --git a/ansible/roles/common/defaults/main.yml b/ansible/roles/common/defaults/main.yml new file mode 100644 index 0000000000..fcda7bd924 --- /dev/null +++ b/ansible/roles/common/defaults/main.yml @@ -0,0 +1,9 @@ +common_packages: + - python3-pip + - curl + - wget + - git + - vim + - htop + - net-tools + - unzip \ 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..b5461257e9 --- /dev/null +++ b/ansible/roles/common/tasks/main.yml @@ -0,0 +1,36 @@ +- name: Common system setup + block: + - name: Update apt cache + apt: + update_cache: yes + cache_valid_time: 3600 + register: apt_update + until: apt_update is success + retries: 3 + delay: 5 + tags: + - packages + + - name: Install common packages + apt: + name: "{{ common_packages }}" + state: present + tags: + - packages + + rescue: + - name: Failed to update cache or install packages + debug: + msg: "An error occurred: {{ ansible_failed_result.msg }}" + + always: + - name: Log completion + copy: + content: "Common role completed at {{ ansible_date_time.iso8601 }}" + dest: /tmp/ansible_common.log + tags: + - never + + become: yes + tags: + - 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..285e71fd52 --- /dev/null +++ b/ansible/roles/docker/defaults/main.yml @@ -0,0 +1,7 @@ +docker_user: "{{ ansible_user }}" +docker_packages: + - docker-ce + - docker-ce-cli + - containerd.io + - docker-buildx-plugin + - docker-compose-plugin \ 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..b2fdfa6384 --- /dev/null +++ b/ansible/roles/docker/handlers/main.yml @@ -0,0 +1,5 @@ +- name: restart docker + service: + name: docker + state: restarted + become: yes \ 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..9fda5a4f47 --- /dev/null +++ b/ansible/roles/docker/tasks/main.yml @@ -0,0 +1,96 @@ +- name: Docker installation block + block: + - name: Remove conflicting packages + apt: + name: + - docker.io + - docker-doc + - docker-compose + - podman-docker + - containerd + - runc + state: absent + ignore_errors: yes + + - name: Install required system packages + apt: + name: + - ca-certificates + - curl + state: present + + - name: Create keyrings directory + file: + path: /etc/apt/keyrings + state: directory + mode: '0755' + + - name: Add Docker GPG key + get_url: + url: https://download.docker.com/linux/ubuntu/gpg + dest: /etc/apt/keyrings/docker.asc + mode: '0644' + force: true + register: gpg_result + until: gpg_result is success + retries: 3 + delay: 5 + + - name: Add Docker APT repository + apt_repository: + repo: "deb [arch={{ ansible_architecture | replace('x86_64','amd64') }} signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable" + state: present + update_cache: yes + + - name: Install Docker packages + apt: + name: "{{ docker_packages }}" + state: present + update_cache: yes + notify: restart docker + + - name: Ensure Docker service is running + service: + name: docker + state: started + enabled: yes + + rescue: + - name: Docker installation failed + debug: + msg: "Docker installation failed: {{ ansible_failed_result.msg }}" + + always: + - name: Ensure Docker enabled after block + service: + name: docker + state: started + enabled: yes + when: ansible_failed_result is not defined + + become: yes + tags: + - docker_install + +- name: Docker configuration block + block: + - name: Add user to docker group + user: + name: "{{ docker_user }}" + groups: docker + append: yes + + - name: Install python3-docker + apt: + name: python3-docker + state: present + + become: yes + tags: + - docker_config + +- name: Docker role complete (always) + debug: + msg: "Docker role finished" + tags: + - docker \ 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..9437206f5f --- /dev/null +++ b/ansible/roles/web_app/defaults/main.yml @@ -0,0 +1,11 @@ +app_name: devops-app +docker_tag: latest +app_port: 8000 +app_internal_port: 8000 +app_restart_policy: unless-stopped +app_env_vars: {} + +compose_project_dir: "/opt/{{ app_name }}" +compose_file: "{{ compose_project_dir }}/docker-compose.yml" + +web_app_wipe: false \ No newline at end of file diff --git a/ansible/roles/web_app/handlers/main.yml b/ansible/roles/web_app/handlers/main.yml new file mode 100644 index 0000000000..7e75326c55 --- /dev/null +++ b/ansible/roles/web_app/handlers/main.yml @@ -0,0 +1,6 @@ +- name: restart app container + docker_container: + name: "{{ app_container_name }}" + state: started + restart: yes + become: yes \ No newline at end of file diff --git a/ansible/roles/web_app/meta/main.yml b/ansible/roles/web_app/meta/main.yml new file mode 100644 index 0000000000..b456d40b27 --- /dev/null +++ b/ansible/roles/web_app/meta/main.yml @@ -0,0 +1,2 @@ +dependencies: + - role: docker \ No newline at end of file diff --git a/ansible/roles/web_app/tasks/main.yml b/ansible/roles/web_app/tasks/main.yml new file mode 100644 index 0000000000..b162c85cef --- /dev/null +++ b/ansible/roles/web_app/tasks/main.yml @@ -0,0 +1,38 @@ +- name: Include wipe tasks + include_tasks: wipe.yml + when: web_app_wipe | bool + tags: + - web_app_wipe + +- name: Deploy application with Docker Compose + block: + - name: Ensure project directory exists + file: + path: "{{ compose_project_dir }}" + state: directory + mode: '0755' + + - name: Template docker-compose.yml + template: + src: docker-compose.yml.j2 + dest: "{{ compose_file }}" + mode: '0644' + + - name: Deploy with docker-compose + community.docker.docker_compose_v2: + project_src: "{{ compose_project_dir }}" + files: + - docker-compose.yml + state: present + pull: always + recreate: auto + + rescue: + - name: Deployment failed + debug: + msg: "Deployment failed: {{ ansible_failed_result.msg }}" + + become: yes + tags: + - app_deploy + - compose \ No newline at end of file diff --git a/ansible/roles/web_app/tasks/wipe.yml b/ansible/roles/web_app/tasks/wipe.yml new file mode 100644 index 0000000000..6647c6f987 --- /dev/null +++ b/ansible/roles/web_app/tasks/wipe.yml @@ -0,0 +1,27 @@ +- name: Wipe application + block: + - name: Stop and remove containers + community.docker.docker_compose_v2: + project_src: "{{ compose_project_dir }}" + state: absent + remove_volumes: yes + ignore_errors: yes + + - name: Remove docker-compose file + file: + path: "{{ compose_file }}" + state: absent + + - name: Remove project directory + file: + path: "{{ compose_project_dir }}" + state: absent + + - name: Log wipe completion + debug: + msg: "Application {{ app_name }} wiped successfully" + + become: yes + when: web_app_wipe | bool + tags: + - web_app_wipe \ No newline at end of file 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..da0fbe23b4 --- /dev/null +++ b/ansible/roles/web_app/templates/docker-compose.yml.j2 @@ -0,0 +1,21 @@ +services: + {{ app_name }}: + image: "{{ docker_image }}:{{ docker_tag }}" + container_name: "{{ app_name }}" + ports: + - "{{ app_port }}:{{ app_internal_port }}" + environment: + - HOST=0.0.0.0 + - PORT={{ app_internal_port }} +{% if app_env_vars is defined and app_env_vars %} +{% for key, value in app_env_vars.items() %} + - {{ key }}={{ value }} +{% endfor %} +{% endif %} + restart: unless-stopped + networks: + - app_network + +networks: + app_network: + driver: bridge \ No newline at end of file diff --git a/app_go/.dockerignore b/app_go/.dockerignore new file mode 100644 index 0000000000..cfb650bdca --- /dev/null +++ b/app_go/.dockerignore @@ -0,0 +1,43 @@ +# Go artifacts +*.exe +*.exe~ +*.dll +*.so +*.dylib +*.test +*.out +*.o +*.prof +*.trace +vendor/ +__pycache__/ + +# Git +.git/ +.gitignore + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Documentation +*.md +docs/ +README.md + +# Docker +Dockerfile* +docker-compose* +.dockerignore + +# Temporary files +*.tmp +*.log +tmp/ +logs/ diff --git a/app_go/Dockerfile b/app_go/Dockerfile new file mode 100644 index 0000000000..2a3e22eea0 --- /dev/null +++ b/app_go/Dockerfile @@ -0,0 +1,42 @@ +# Stage 1: Builder - full build environment +FROM golang:1.21-alpine AS builder + +# Install system dependencies for build (git for go mod download) +RUN apk add --no-cache git ca-certificates + +# Set working directory +WORKDIR /app + +# Copy Go module files +COPY go.mod ./ + +# Download Go module dependencies +RUN go mod download + +# Copy application source code +COPY . . + +# Build Go application with optimizations +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ + -a \ + -ldflags="-w -s -extldflags '-static'" \ + -o devops-info-service . + +# Stage 2: Minimal runtime +FROM scratch + +# Copy CA certificates from builder for HTTPS support +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ + +# Copy the compiled binary from builder +COPY --from=builder /app/devops-info-service /app/devops-info-service + +# Expose port +EXPOSE 5000 + +# Set environment variables +ENV HOST=0.0.0.0 +ENV PORT=5000 + +# Run the application +CMD ["/app/devops-info-service"] \ No newline at end of file diff --git a/app_go/README.md b/app_go/README.md new file mode 100644 index 0000000000..292daf65ab --- /dev/null +++ b/app_go/README.md @@ -0,0 +1,97 @@ +# DevOps Info Service (Go) +## Overview +A Go-based web service designed to furnish details about itself and its operational environment. This compiled version of the service is optimized for containerization and multi-stage Docker builds, offering improved performance and smaller deployment footprints compared to interpreted languages. + +## Prerequisites +- Go 1.21 or higher +- Git (for dependency management) + +## Installation +1. Clone repository: + +```bash +# Clone the project +git clone https://github.com/s3rap1s/DevOps-Core-Course.git +cd DevOps-Core-Course/app_go + +# Download dependencies +go mod download + +# Build the application +go build -o devops-info-service +``` + +## Running the Application +```bash +# Default configuration +./devops-info-service + +# With custom port +PORT=8080 ./devops-info-service + +# With custom port and host +HOST=127.0.0.1 PORT=3000 ./devops-info-service + +# Run directly without building +go run main.go +Building for Different Platforms +bash +# Build for current platform +go build -o devops-info-service +``` + +## API Endpoints +### GET / +Return comprehensive service and system information: + +```json +{ + "service": { + "name": "devops-info-service", + "version": "1.0.0", + "description": "DevOps course info service", + "framework": "Go" + }, + "system": { + "hostname": "my-laptop", + "platform": "linux", + "platform_version": "Linux Kernel", + "architecture": "amd64", + "cpu_count": 8, + "go_version": "go1.21.4" + }, + "runtime": { + "uptime_seconds": 3600, + "uptime_human": "1 hour, 0 minutes", + "current_time": "2026-01-07T14:30:00.000Z", + "timezone": "UTC" + }, + "request": { + "client_ip": "127.0.0.1:12345", + "user_agent": "curl/7.81.0", + "method": "GET", + "path": "/" + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"} + ] +} +``` + +### GET /health +Simple health endpoint for monitoring: + +```json +{ + "status": "healthy", + "timestamp": "2024-01-15T14:30:00.000Z", + "uptime_seconds": 3600 +} +``` + +## Configuration +| Variable | Default | Description | +| -------- | --------- | ---------------------------- | +| `HOST` | `0.0.0.0` | Network interface to bind | +| `PORT` | `5000` | Port to listen on | \ No newline at end of file diff --git a/app_go/docs/GO.md b/app_go/docs/GO.md new file mode 100644 index 0000000000..b42a88d6a8 --- /dev/null +++ b/app_go/docs/GO.md @@ -0,0 +1,18 @@ +# Language Justification +## My Choice: Go +I selected **Go** as the compiled language for the bonus task implementation. Here's why: + +**Comparison Table:** + +| Criteria | Go | Rust | Java | C# | +|----------|----|------|------|----| +|Learning Curve | Low | High | Medium | Medium | +|Development Speed | High | Low | Medium | Medium | +|Standard Library | Excellent | Good | Extensive | Extensive | +|Performance | Excellent | Outstanding | Good | Good | +|Binary Size | ~7 MB | ~3 MB | ~40 MB | ~30 MB | +|Memory Safety | GC | Compile-time | GC | GC | +| **Choice for Bonus** | **✓** | | | | + +**Justification:** +Go offers the perfect balance for a DevOps service: it compiles to a single static binary with no runtime dependencies, has excellent concurrency support, and provides a rich standard library including HTTP server functionality. Its simplicity and fast compilation make it ideal for the iterative development required in this course. Go is also widely used in the DevOps ecosystem (Docker, Kubernetes, Prometheus), making it a relevant choice. \ No newline at end of file diff --git a/app_go/docs/LAB01.md b/app_go/docs/LAB01.md new file mode 100644 index 0000000000..4b93018d26 --- /dev/null +++ b/app_go/docs/LAB01.md @@ -0,0 +1,293 @@ +# Lab 1 — DevOps Info Service: Web Application Development on Go +## Language Selection +### My Choice: Go +I selected **Go** as the compiled language for the bonus task implementation. Here's why: + +**Comparison Table:** + +| Criteria | Go | Rust | Java | C# | +|----------|----|------|------|----| +|Learning Curve | Low | High | Medium | Medium | +|Development Speed | High | Low | Medium | Medium | +|Standard Library | Excellent | Good | Extensive | Extensive | +|Performance | Excellent | Outstanding | Good | Good | +|Binary Size | ~7 MB | ~3 MB | ~40 MB | ~30 MB | +|Memory Safety | GC | Compile-time | GC | GC | +| **Choice for Bonus** | **✓** | | | | + +**Justification:** +Go offers the perfect balance for a DevOps service: it compiles to a single static binary with no runtime dependencies, has excellent concurrency support, and provides a rich standard library including HTTP server functionality. Its simplicity and fast compilation make it ideal for the iterative development required in this course. Go is also widely used in the DevOps ecosystem (Docker, Kubernetes, Prometheus), making it a relevant choice. + +## Best Practices Applied +### 1. Clean Code Organization +```go +// Clear imports grouping +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "runtime" + "time" +) + +// Descriptive function names +func getSystemInfo() System { + hostname, err := os.Hostname() + if err != nil { + hostname = "unknown" + } + + return System{ + Hostname: hostname, + Platform: runtime.GOOS, + PlatformVersion: getOSVersion(), + Architecture: runtime.GOARCH, + CPUCount: runtime.NumCPU(), + GoVersion: runtime.Version(), + } +} +``` +**Importance:** Clean organization with clear separation of concerns makes the code maintainable and testable. Following Go conventions (camelCase, exported/unexported identifiers) ensures consistency. + +### 2. Comprehensive Error Handling +```go +func notFoundHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + json.NewEncoder(w).Encode(map[string]string{ + "error": "Not Found", + "message": "Endpoint does not exist", + }) + + log.Printf("404 Not Found: %s", r.URL.Path) +} +``` +**Importance:** Proper error handling prevents application crashes and provides meaningful feedback to API consumers. Each error type returns appropriate HTTP status codes and structured JSON responses. + +### 3. Structured Logging +```go +func main() { + // Read environment variables + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + host := os.Getenv("HOST") + if host == "" { + host = "0.0.0.0" + } + + log.Printf("Starting DevOps Info Service on %s:%s", host, port) + log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%s", host, port), nil)) +} +``` +**Importance:** Logging provides visibility into application behavior and startup configuration. The standard log package is sufficient for this simple service, though larger applications might use structured logging libraries. + +### 4. Configuration via Environment Variables +```go +port := os.Getenv("PORT") +if port == "" { + port = "5000" +} +``` +**Importance:** Following the 12-factor app methodology, configuration via environment variables makes the application portable across different environments without recompilation. + +### 5. Minimal Dependencies +```go +// go.mod - only Go standard library is used +module devops-info-service + +go 1.21 +``` +**Importance:** Using only the standard library eliminates dependency management overhead and reduces security vulnerabilities. The resulting binary is self-contained. + +### 6. Static Typing and Compile-Time Safety +```go +type ServiceInfo struct { + Service Service `json:"service"` + System System `json:"system"` + Runtime Runtime `json:"runtime"` + Request Request `json:"request"` + Endpoints []Endpoint `json:"endpoints"` +} +``` +**Importance:** Static typing catches many errors at compile time rather than runtime, improving reliability. Struct tags provide clear mapping between Go structs and JSON output. + +## API Documentation +### Endpoint 1: GET / +**Description:** Returns comprehensive service information, system details, runtime data, and request metadata. + +**Request:** +```bash +curl http://localhost:8080/ +``` +**Response (example):** +```json +{ + "service": { + "name": "devops-info-service", + "version": "1.0.0", + "description": "DevOps course info service", + "framework": "Go" + }, + "system": { + "hostname": "ubuntu-dev", + "platform": "linux", + "platform_version": "Linux Kernel", + "architecture": "amd64", + "cpu_count": 8, + "go_version": "go1.21.4" + }, + "runtime": { + "uptime_seconds": 125, + "uptime_human": "0 hours, 2 minutes", + "current_time": "2026-01-27T10:30:00.000Z", + "timezone": "UTC" + }, + "request": { + "client_ip": "127.0.0.1:54321", + "user_agent": "curl/7.88.1", + "method": "GET", + "path": "/" + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"} + ] +} +``` +### Endpoint 2: GET /health +**Description:** Health check endpoint for monitoring system. Always returns HTTP 200 with service status. + +**Request:** +```bash +curl http://localhost:8080/health +``` +**Response:** +```json +{ + "status": "healthy", + "timestamp": "2026-01-27T10:30:00.000Z", + "uptime_seconds": 125 +} +``` +### Testing Commands +1. **Basic endpoint test:** + +```bash +curl http://localhost:8080/ +``` + +2. **Health check test:** +```bash +curl http://localhost:8080/health +``` +3. **Pretty-printed output:** +```bash +curl http://localhost:8080/ | jq . +``` +4. **Custom configuration:** +```bash +PORT=8080 ./devops-info-service +curl http://localhost:8080/health +``` + +5. **Error simulation:** +```bash +curl -v http://localhost:8080/nonexistent +# Should return 404 error +``` +## Build Process +### Compilation +```bash +# Initialize Go module +go mod init devops-info-service + +# Build standard binary +go build -o devops-info-service +``` +###Running +```bash +# Run the compiled binary +./devops-info-service + +# Run with custom configuration +HOST=127.0.0.1 PORT=3000 ./devops-info-service + +# Run directly (without building) +go run main.go +``` +## Testing Evidence +### Main endpoint: +![Main Endpoint](screenshots/01-main-endpoint.png) + +### Health check: +![Health Check](screenshots/02-health-check.png) + +### Formatted output: +![Formatted output](screenshots/03-formatted-output.png) + +## Challenges & Solutions +### Challenge 1: HTTP Handler Registration +**Problem:** Go's http.HandleFunc doesn't allow multiple registrations for the same path, unlike Flask's decorator pattern. + +**Solution:** Implemented a routing check within the main handler: +```go +func mainHandler(w http.ResponseWriter, r *http.Request) { + // Handle only root path + if r.URL.Path != "/" { + notFoundHandler(w, r) + return + } + // ... rest of handler +} +``` +### Challenge 2: Platform Version Detection +**Problem:** Go's standard library doesn't provide detailed OS version information like Python's platform.release(). + +**Solution:** Created a simple mapping function: +```go +func getOSVersion() string { + switch runtime.GOOS { + case "linux": + return "Linux Kernel" + case "darwin": + return "macOS" + case "windows": + return "Windows" + default: + return runtime.GOOS + } +} +``` +### Challenge 3: Uptime Formatting +**Problem:** Converting seconds to human-readable format required manual calculation. + +**Solution:** Implemented a reusable function: +```go +func getUptime() (int, string) { + duration := time.Since(startTime) + seconds := int(duration.Seconds()) + + hours := seconds / 3600 + minutes := (seconds % 3600) / 60 + + return seconds, fmt.Sprintf("%d hours, %d minutes", hours, minutes) +} +``` +### Challenge 4: JSON Serialization +**Problem:** Ensuring proper JSON field naming and null handling. + +**Solution:** Used struct tags and proper initialization: +```go +type System struct { + Hostname string `json:"hostname"` + Platform string `json:"platform"` + PlatformVersion string `json:"platform_version"` + // ... other fields +} +``` + diff --git a/app_go/docs/LAB02.md b/app_go/docs/LAB02.md new file mode 100644 index 0000000000..9cec8ec40f --- /dev/null +++ b/app_go/docs/LAB02.md @@ -0,0 +1,252 @@ +# Lab 2 Bonus — Multi-Stage Docker Build for Go Application + +## Multi-Stage Strategy + +### Stage 1: Builder +```dockerfile +# Stage 1: Builder - full build environment +FROM golang:1.21-alpine AS builder + +# Install system dependencies for build (git for go mod download) +RUN apk add --no-cache git ca-certificates + +# Set working directory +WORKDIR /app + +# Copy Go module files +COPY go.mod ./ + +# Download Go module dependencies +RUN go mod download + +# Copy application source code +COPY . . + +# Build Go application with optimizations +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ + -a \ + -ldflags="-w -s -extldflags '-static'" \ + -o devops-info-service . +``` + +**Purpose:** Complete build environment containing: +- Go 1.21 compiler and standard library +- Git for dependency management +- All source code and build tools +- Temporary workspace for compilation + +### Stage 2: Runtime +```dockerfile +FROM scratch + +# Copy CA certificates from builder for HTTPS support +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ + +# Copy the compiled binary from builder +COPY --from=builder /app/devops-info-service /app/devops-info-service + +# Expose port +EXPOSE 5000 + +# Set environment variables +ENV HOST=0.0.0.0 +ENV PORT=5000 + +# Run the application +CMD ["/app/devops-info-service"] +``` + +**Purpose:** Absolute minimal runtime environment containing only: +- Statically compiled Go binary +- CA certificates for HTTPS/TLS support +- No operating system, shell, or package manager + +## Size Comparison + +### Image Size Analysis +| Component | Size | Contents | +|-----------|------|----------| +| **Builder Stage** | ~350MB | Full Go 1.21 SDK + Alpine + build tools | +| **Runtime Stage** | **7.16MB** | Static binary + CA certificates | +| **Size Reduction** | **~98%** | 350MB → 7.16MB | + +### Detailed Breakdown +- **Builder image:** Uses `golang:1.21-alpine` (~350MB with build tools) +- **Final image:** Uses `scratch` (0MB base) + binary + certificates +- **Binary size:** ~7.16MB (statically compiled Go application + CA certificate) + +## Why Multi-Stage Builds Matter for Compiled Languages + +### 1. Drastic Size Reduction +Compiled languages like Go have a fundamental advantage: they produce standalone binaries. Multi-stage builds leverage this by: +- **Separating concerns:** Build environment (large) vs runtime (minimal) +- **Eliminating build tools:** Compiler, linker, SDK removed from production +- **Removing dependencies:** Only the binary and absolute essentials remain + +### 2. Enhanced Security +```dockerfile +FROM scratch # No operating system, no shell, no package manager +``` + +**Security benefits:** +- **No shell access:** Cannot spawn shells even if compromised +- **Immutable runtime:** Binary cannot be modified without rebuilding +- **Principle of least privilege:** Only what's absolutely necessary + +### 3. Production Performance +- **Faster deployment:** Smaller images download quicker +- **Reduced storage:** Less disk space required across development/staging/production +- **Lower memory footprint:** Minimal OS overhead +- **Quick startup:** No initialization of unused services + +## Terminal Output + +### Build Process Output +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ docker build -t devops-info-service:go . +[+] Building 5.1s (14/14) FINISHED docker:default + => [internal] load build definition from Dockerfile 0.0s + => => transferring dockerfile: 1.00kB 0.0s + => [internal] load metadata for docker.io/library/golang:1.21-alpine 0.7s + => [internal] load .dockerignore 0.0s + => => transferring context: 359B 0.0s + => [builder 1/7] FROM docker.io/library/golang:1.21-alpine@sha256:2414035b086e3c42b99654c8b26e6f5b1b1598080d65fd03c7f499552ff4dc94 0.0s + => => resolve docker.io/library/golang:1.21-alpine@sha256:2414035b086e3c42b99654c8b26e6f5b1b1598080d65fd03c7f499552ff4dc94 0.0s + => [internal] load build context 0.0s + => => transferring context: 54B 0.0s + => CACHED [builder 2/7] RUN apk add --no-cache git ca-certificates 0.0s + => CACHED [builder 3/7] WORKDIR /app 0.0s + => CACHED [builder 4/7] COPY go.mod ./ 0.0s + => CACHED [builder 5/7] RUN go mod download 0.0s + => CACHED [builder 6/7] COPY . . 0.0s + => [builder 7/7] RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -ldflags="-w -s -extldflags '-static'" -o devops-info-service . 3.9s + => [stage-1 1/2] COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 0.0s + => [stage-1 2/2] COPY --from=builder /app/devops-info-service /app/devops-info-service 0.0s + => exporting to image 0.4s + => => exporting layers 0.3s + => => exporting manifest sha256:4e1764a6a80bfc8666f97655b398a31766e6ef0b7e113b73651ca44601a369e5 0.0s + => => exporting config sha256:07f16274913e502fcb7339751611566f733555d340310768666604f24375006b 0.0s + => => exporting attestation manifest sha256:594b42605a1d485598b5ca39be853c1e154958e927a235027e0ca1b5fce2efa9 0.0s + => => exporting manifest list sha256:c5f945015fb0dfd3f762151c64c5393121944441d08e191e5a7533aadcf4f4eb 0.0s + => => naming to docker.io/library/devops-info-service:go 0.0s + => => unpacking to docker.io/library/devops-info-service:go +``` + +### Image Size Verification +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ docker images | grep devops-info-service +WARNING: This output is designed for human readability. For machine-readable output, please use --format. +devops-info-service:go c5f945015fb0 7.16MB 2.2MB U +devops-info-service:python 4b08b6e2f063 199MB 48.1MB +s3rap1s/devops-info-service:python ef074c1a118d 199MB 48.1MB + +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ docker history devops-info-service:go +IMAGE CREATED CREATED BY SIZE COMMENT +c5f945015fb0 14 minutes ago CMD ["/app/devops-info-service"] 0B buildkit.dockerfile.v0 + 14 minutes ago ENV PORT=5000 0B buildkit.dockerfile.v0 + 14 minutes ago ENV HOST=0.0.0.0 0B buildkit.dockerfile.v0 + 14 minutes ago EXPOSE [5000/tcp] 0B buildkit.dockerfile.v0 + 14 minutes ago COPY /app/devops-info-service /app/devops-in… 4.72MB buildkit.dockerfile.v0 + 14 minutes ago COPY /etc/ssl/certs/ca-certificates.crt /etc… 238kB buildkit.dockerfile.v0 +``` + +### Runtime Testing +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ docker run -d --name devops-go -p 5000:5000 devops-info-service:go +0d2cb36ff83b03fca8090248aa3a6fe1beba1e879617a8dd2e5a9c3a588e8c1c + +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ curl http://localhost:5000/ +{"service":{"name":"devops-info-service","version":"1.0.0","description":"DevOps course info service","framework":"Go"},"system":{"hostname":"0d2cb36ff83b","platform":"linux","platform_version":"Linux Kernel","architecture":"amd64","cpu_count":12,"go_version":"go1.21.13"},"runtime":{"uptime_seconds":17,"uptime_human":"0 hours, 0 minutes","current_time":"2026-01-31T20:20:36Z","timezone":"UTC"},"request":{"client_ip":"172.17.0.1:50750","user_agent":"curl/8.18.0","method":"GET","path":"/"},"endpoints":[{"path":"/","method":"GET","description":"Service information"},{"path":"/health","method":"GET","description":"Health check"}]} + +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ curl http://localhost:5000/health +{"status":"healthy","timestamp":"2026-01-31T20:21:20Z","uptime_seconds":61} + +s3rap1s in ~/devops/DevOps-Core-Course/app_go on lab01 ● ● λ docker logs devops-go +2026/01/31 20:20:19 Starting DevOps Info Service on 0.0.0.0:5000 +2026/01/31 20:20:34 Health check from 172.17.0.1:50742 +2026/01/31 20:20:36 Request: GET / from 172.17.0.1:50750 +2026/01/31 20:21:13 404 Not Found: /helath +2026/01/31 20:21:20 Health check from 172.17.0.1:38286 +``` + +## Technical Explanation of Each Stage + +### Stage 1: Builder (`golang:1.21-alpine`) +**Purpose:** Provide complete compilation environment + +**Key operations:** +1. **Base setup:** Alpine Linux with Go 1.21 toolchain +2. **Dependencies:** Install git and CA certificates +3. **Module management:** Download Go dependencies with caching +4. **Compilation:** Build optimized static binary with: + - `CGO_ENABLED=0`: Disable CGO for pure Go static binary + - `-ldflags="-w -s"`: Strip debug symbols and DWARF tables + - `-extldflags '-static'`: Force static linking + - `-a`: Force rebuilding of packages + +**Output:** `/app/devops-info-service` (6.9MB static binary) + +### Stage 2: Runtime (`scratch`) +**Purpose:** Provide minimal production runtime + +**Key operations:** +1. **Base image:** `scratch` (empty filesystem) +2. **Binary copy:** Transfer compiled binary from builder +3. **Certificates:** Copy CA certificates for TLS/HTTPS support +4. **Configuration:** Set environment variables and expose port + +**Output:** Production-ready container image (7.16MB) + +## Security Benefits of Smaller Images + +### Specific Security Advantages +1. **No shell:** Cannot execute arbitrary commands or spawn shells +2. **Immutable filesystem:** Only the binary exists, cannot be modified +3. **Minimal CVE surface:** No packages = no vulnerabilities to patch +4. **Isolated execution:** Runs as PID 1 with no background services +5. **Resource limits:** Minimal memory/cpu usage reduces DoS impact + +## Why FROM scratch? Trade-offs and Decisions + +### Why `scratch` Was Chosen +```dockerfile +FROM scratch # Instead of alpine, distroless, or other minimal bases +``` + +**Advantages:** +1. **Absolute minimalism:** 0MB base, only binary + certs +2. **Maximum security:** No OS, no shell, no utilities +3. **Great for static binaries:** Go compiles to fully static executables + +### Trade-offs Considered +| Base Image | Size | Pros | Cons | Decision | +|------------|------|------|------|----------| +| **scratch** | 0MB | Max security, minimal size | No debugging tools, no shell | ✅ **Chosen** | +| **alpine** | 5.5MB | Shell for debugging, small | Larger, more attack surface | Rejected | +| **distroless** | 20MB | Secure | Much larger than scratch | Rejected | + +## Analysis of Size Reduction and Why It Matters + +### Why Size Reduction Matters +1. **Cost efficiency:** 98% reduction in storage and bandwidth costs +2. **Deployment speed:** Images deploy in seconds instead of minutes +3. **Developer productivity:** Faster CI/CD pipeline execution +4. **Environmental impact:** Less energy for storage and transfer +5. **Edge computing:** Suitable for resource-constrained environments + +## Challenges and Solutions + +### Challenge: Certificate Management with `scratch` +**Problem:** `scratch` has no CA certificates, breaking HTTPS calls from the application. + +**Solution:** Copy certificates from builder stage: +```dockerfile +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +``` + +## What I Learned + +1. **Multi-stage builds** are transformative for compiled languages, enabling near-zero runtime overhead +2. **Static compilation** is powerful but requires careful dependency management +3. **Security through minimalism** is achievable with `scratch` base images +4. **Trade-offs exist** between debuggability and security/minimalism diff --git a/app_go/docs/screenshots/01-main-endpoint.png b/app_go/docs/screenshots/01-main-endpoint.png new file mode 100644 index 0000000000..6acabfa3cf Binary files /dev/null and b/app_go/docs/screenshots/01-main-endpoint.png differ diff --git a/app_go/docs/screenshots/02-health-check.png b/app_go/docs/screenshots/02-health-check.png new file mode 100644 index 0000000000..f905599cf0 Binary files /dev/null and b/app_go/docs/screenshots/02-health-check.png differ diff --git a/app_go/docs/screenshots/03-formatted-output.png b/app_go/docs/screenshots/03-formatted-output.png new file mode 100644 index 0000000000..f4dd6737db Binary files /dev/null and b/app_go/docs/screenshots/03-formatted-output.png differ diff --git a/app_go/go.mod b/app_go/go.mod new file mode 100644 index 0000000000..307ce0d1c5 --- /dev/null +++ b/app_go/go.mod @@ -0,0 +1,3 @@ +module devops-info-service + +go 1.21 diff --git a/app_go/main.go b/app_go/main.go new file mode 100644 index 0000000000..7b0e355b6c --- /dev/null +++ b/app_go/main.go @@ -0,0 +1,205 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "runtime" + "time" +) + +// Data structures +type ServiceInfo struct { + Service Service `json:"service"` + System System `json:"system"` + Runtime Runtime `json:"runtime"` + Request Request `json:"request"` + Endpoints []Endpoint `json:"endpoints"` +} + +type Service struct { + Name string `json:"name"` + Version string `json:"version"` + Description string `json:"description"` + Framework string `json:"framework"` +} + +type System struct { + Hostname string `json:"hostname"` + Platform string `json:"platform"` + PlatformVersion string `json:"platform_version"` + Architecture string `json:"architecture"` + CPUCount int `json:"cpu_count"` + GoVersion string `json:"go_version"` +} + +type Runtime struct { + UptimeSeconds int `json:"uptime_seconds"` + UptimeHuman string `json:"uptime_human"` + CurrentTime string `json:"current_time"` + Timezone string `json:"timezone"` +} + +type Request struct { + ClientIP string `json:"client_ip"` + UserAgent string `json:"user_agent"` + Method string `json:"method"` + Path string `json:"path"` +} + +type Endpoint struct { + Path string `json:"path"` + Method string `json:"method"` + Description string `json:"description"` +} + +type HealthResponse struct { + Status string `json:"status"` + Timestamp string `json:"timestamp"` + UptimeSeconds int `json:"uptime_seconds"` +} + +// Global variables +var startTime time.Time + +func init() { + startTime = time.Now() +} + +// Helper functions +func getSystemInfo() System { + hostname, err := os.Hostname() + if err != nil { + hostname = "unknown" + } + + return System{ + Hostname: hostname, + Platform: runtime.GOOS, + PlatformVersion: getOSVersion(), + Architecture: runtime.GOARCH, + CPUCount: runtime.NumCPU(), + GoVersion: runtime.Version(), + } +} + +func getOSVersion() string { + switch runtime.GOOS { + case "linux": + return "Linux Kernel" + case "darwin": + return "macOS" + case "windows": + return "Windows" + default: + return runtime.GOOS + } +} + +func getUptime() (int, string) { + duration := time.Since(startTime) + seconds := int(duration.Seconds()) + + hours := seconds / 3600 + minutes := (seconds % 3600) / 60 + + return seconds, fmt.Sprintf("%d hours, %d minutes", hours, minutes) +} + +func getCurrentTime() string { + return time.Now().UTC().Format(time.RFC3339) +} + +// HTTP handlers +func mainHandler(w http.ResponseWriter, r *http.Request) { + // Handle only root path + if r.URL.Path != "/" { + notFoundHandler(w, r) + return + } + + systemInfo := getSystemInfo() + uptimeSeconds, uptimeHuman := getUptime() + + response := ServiceInfo{ + Service: Service{ + Name: "devops-info-service", + Version: "1.0.0", + Description: "DevOps course info service", + Framework: "Go", + }, + System: systemInfo, + Runtime: Runtime{ + UptimeSeconds: uptimeSeconds, + UptimeHuman: uptimeHuman, + CurrentTime: getCurrentTime(), + Timezone: "UTC", + }, + Request: Request{ + ClientIP: r.RemoteAddr, + UserAgent: r.UserAgent(), + Method: r.Method, + Path: r.URL.Path, + }, + Endpoints: []Endpoint{ + {Path: "/", Method: "GET", Description: "Service information"}, + {Path: "/health", Method: "GET", Description: "Health check"}, + }, + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(response) + + log.Printf("Request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr) +} + +func healthHandler(w http.ResponseWriter, r *http.Request) { + uptimeSeconds, _ := getUptime() + + response := HealthResponse{ + Status: "healthy", + Timestamp: getCurrentTime(), + UptimeSeconds: uptimeSeconds, + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(response) + + log.Printf("Health check from %s", r.RemoteAddr) +} + +func notFoundHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + json.NewEncoder(w).Encode(map[string]string{ + "error": "Not Found", + "message": "Endpoint does not exist", + }) + + log.Printf("404 Not Found: %s", r.URL.Path) +} + +// Main function +func main() { + // Read environment variables + port := os.Getenv("PORT") + if port == "" { + port = "5000" + } + + host := os.Getenv("HOST") + if host == "" { + host = "0.0.0.0" + } + + // Setup HTTP routes + http.HandleFunc("/", mainHandler) + http.HandleFunc("/health", healthHandler) + + // Start server + addr := fmt.Sprintf("%s:%s", host, port) + log.Printf("Starting DevOps Info Service on %s", addr) + log.Fatal(http.ListenAndServe(addr, nil)) +} \ No newline at end of file diff --git a/app_python/.dockerignore b/app_python/.dockerignore new file mode 100644 index 0000000000..df2ec2cfb1 --- /dev/null +++ b/app_python/.dockerignore @@ -0,0 +1,39 @@ +# Python +__pycache__/ +*.py[cod] +*.pyo +*.so +.Python +venv/ +env/ +.venv/ +.env +*.log + +# Git +.git/ +.gitignore + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Documentation +*.md +docs/ +README.md + +# Tests +tests/ +test*.py + +# Docker +Dockerfile* +docker-compose* +.dockerignore \ No newline at end of file diff --git a/app_python/.gitignore b/app_python/.gitignore new file mode 100644 index 0000000000..4de420a8f7 --- /dev/null +++ b/app_python/.gitignore @@ -0,0 +1,12 @@ +# Python +__pycache__/ +*.py[cod] +venv/ +*.log + +# IDE +.vscode/ +.idea/ + +# OS +.DS_Store \ No newline at end of file diff --git a/app_python/Dockerfile b/app_python/Dockerfile new file mode 100644 index 0000000000..3de1bb9253 --- /dev/null +++ b/app_python/Dockerfile @@ -0,0 +1,56 @@ +# Dockerfile for Python Application with Virtual Environment +FROM python:3.13-slim AS builder + +# Installing system dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc \ + && rm -rf /var/lib/apt/lists/* + +# Installing the working directory +WORKDIR /app + +# Creating a virtual environment +RUN python -m venv /opt/venv + +# Activating the virtual environment +ENV PATH="/opt/venv/bin:$PATH" + +# Copying requirements file +COPY requirements.txt . +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements.txt + +# Final stage: Copying the virtual environment and application code +FROM python:3.13-slim + +# Creating non-root user and group +RUN groupadd -r appgroup && useradd -r -g appgroup appuser + +# Setting the working directory +WORKDIR /app + +# Copying the virtual environment from the builder stage +COPY --from=builder /opt/venv /opt/venv + +# Copying the application code +COPY . . + +# Setting permissions for the application directory +RUN chown -R appuser:appgroup /app && chmod -R 755 /app + +# Switching to non-root user +USER appuser + +# Setting the PATH to include the virtual environment +ENV PATH="/opt/venv/bin:$PATH" + +# Opening the port for the application +EXPOSE 5000 + +# Setting environment variables +ENV HOST=0.0.0.0 +ENV PORT=5000 +ENV PYTHONUNBUFFERED=1 + +# Running the application +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..3dc57784f3 --- /dev/null +++ b/app_python/README.md @@ -0,0 +1,225 @@ +# DevOps Info Service + +## Overview +A Python-based web service designed to furnish details about itself and its operational environment. This service serves as a foundation for subsequent experiments in containerization, continuous integration and continuous deployment (CI/CD), monitoring, and deployment processes. + +## CI/CD Pipeline +![Python CI/CD](https://github.com/s3rap1s/DevOps-Core-Course/actions/workflows/python-ci.yml/badge.svg) + +### Overview +This project uses GitHub Actions for continuous integration and deployment. The pipeline includes: + +1. **Code Quality Checks** + - Linting with flake8 + - Code formatting with black + - Security scanning with Snyk + +2. **Testing** + - Unit tests with pytest + - Test coverage tracking + - 90%+ code coverage requirement + +3. **Docker Build & Deployment** + - Multi-stage Docker builds + - Automated tagging with Calendar Versioning + - Push to Docker Hub + +### Versioning Strategy +We use **Calendar Versioning (CalVer)** with the format `YYYY.MM.MICRO`: + +- **YYYY.MM.DD** - Specific date of build +- **YYYY.MM.MICRO** - Version with micro release number +- **latest** - Most recent stable build + + +## Prerequisites +- Python 3.11 or higher +- pip (Python Package manager) + +## Installation +1. Clone repository: +```bash +# Clone the project +git clone https://github.com/s3rap1s/DevOps-Core-Course.git +cd DevOps-Core-Course/app_python + +# Create virtual environment +python3 -m venv venv +source venv/bin/activate # on Linux / macOs or .\venv\Scripts\Activate.ps1 on windows + +# Install dependencies +pip install -r requirements.txt +``` + +## Running the Application + +```bash +# Default configuration +python app.py + +# With custom port +PORT=8080 python app.py + +# With custom port and host +HOST=127.0.0.1 PORT=3000 python app.py + +# With custom data and config paths +DATA_DIR=./data CONFIG_FILE=./config/config.json python app.py +``` + +## Testing the Application +```bash +pytest # Run all tests +pytest --cov=app --cov-report=term-missing # Run with coverage +``` + +## Docker + +This application is containerized and available as a Docker image. + +### Building the Image Locally + +```bash +docker build -t devops-info-service:latest . +``` + +### Running a Container + +```bash +# Run with default port mapping +docker run -d -p 5000:5000 devops-info-service:latest + +# Run with custom port +docker run -d -p 8080:5000 devops-info-service:latest + +# Run with environment variables +docker run -d -p 3000:3000 -e PORT=3000 -e HOST=0.0.0.0 devops-info-service:latest + +# Run with persistent visits storage +docker run -d -p 5000:5000 \ + -e DATA_DIR=/app/data \ + -v devops-info-service-data:/app/data \ + devops-info-service:latest +``` + +### Pulling from Docker Hub + +```bash +# Pull the latest version +docker pull your-username/devops-info-service:latest + +# Run pulled image +docker run -d -p 5000:5000 your-username/devops-info-service:latest +``` + +### Environment Variables in Docker +When running in Docker, you can pass environment variables using the `-e` flag: + +```bash +docker run -d -p 5000:5000 \ + -e HOST=0.0.0.0 \ + -e PORT=5000 \ + -e DEBUG=false \ + devops-info-service:latest +``` + +## API Endpoints + +### `GET /` +Return comprehensive service and system information: + +```json +{ + "service": { + "name": "devops-info-service", + "version": "2.0.0", + "description": "DevOps course info service", + "framework": "Flask" + }, + "system": { + "hostname": "my-laptop", + "platform": "Linux", + "platform_version": "Ubuntu 24.04", + "architecture": "x86_64", + "cpu_count": 8, + "python_version": "3.13.1" + }, + "runtime": { + "uptime_seconds": 3600, + "uptime_human": "1 hour, 0 minutes", + "current_time": "2026-01-07T14:30:00.000Z", + "timezone": "UTC", + "visits_count": 12 + }, + "request": { + "client_ip": "127.0.0.1", + "user_agent": "curl/7.81.0", + "method": "GET", + "path": "/" + }, + "configuration": { + "file": { + "application_name": "devops-info-service", + "environment": "development", + "settings": { + "featureGreeting": true, + "maxVisitsDisplay": 10 + } + }, + "environment": { + "APP_ENV": "development", + "LOG_LEVEL": "info", + "FEATURE_GREETINGS": "true", + "CONFIG_FILE": "/config/config.json", + "DATA_DIR": "/data" + } + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"}, + {"path": "/visits", "method": "GET", "description": "Visit counter"}, + {"path": "/metrics", "method": "GET", "description": "Prometheus metrics"} + ] +} +``` + +### `GET /health` + +Simple health endpoint for monitoring: + +```json +{ + "status": "healthy", + "timestamp": "2024-01-15T14:30:00.000Z", + "uptime_seconds": 3600 +} +``` + +### `GET /visits` + +Returns the current persisted visit counter: + +```json +{ + "visits": 12, + "file": "/data/visits" +} +``` + + +## Configuration + +| Variable | Default | Description | +| -------- | --------- | ---------------------------- | +| `HOST` | `0.0.0.0` | Network interface to bind | +| `PORT` | `5000` | Port to listen on | +| `DEBUG` | `false` | Enable debug mode | +| `DATA_DIR` | `./data` | Directory used for visits persistence | +| `VISITS_FILE` | `/visits` | File storing visit counter | +| `CONFIG_FILE` | `./config/config.json` | JSON config file path | + +## Persistence + +The root endpoint increments a counter stored in the visits file. The `/visits` endpoint returns the current value without incrementing it. + +For local Docker Compose testing, the application container mounts a persistent volume to keep `/app/data/visits` across container restarts. diff --git a/app_python/app.py b/app_python/app.py new file mode 100644 index 0000000000..7b9e0d983b --- /dev/null +++ b/app_python/app.py @@ -0,0 +1,323 @@ +""" +DevOps Info Service +Main application module +""" + +import os +import socket +import platform +import logging +import time +import json +import tempfile +from threading import Lock +from datetime import datetime, timezone +from flask import Flask, Response, g, jsonify, request +from prometheus_client import CONTENT_TYPE_LATEST, Counter, Gauge, Histogram, generate_latest +from pythonjsonlogger import jsonlogger + +# Flask app initialization +app = Flask(__name__) + +# Configuration via environment variables +HOST = os.getenv("HOST", "0.0.0.0") +PORT = int(os.getenv("PORT", 5000)) +DEBUG = os.getenv("DEBUG", "False").lower() == "true" +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +DATA_DIR = os.getenv("DATA_DIR", os.path.join(BASE_DIR, "data")) +VISITS_FILE = os.getenv("VISITS_FILE", os.path.join(DATA_DIR, "visits")) +CONFIG_FILE = os.getenv("CONFIG_FILE", os.path.join(BASE_DIR, "config", "config.json")) +VISITS_LOCK = Lock() + +# Application startup time +START_TIME = datetime.now(timezone.utc) + +# Prometheus metrics +HTTP_REQUESTS_TOTAL = Counter( + "http_requests_total", + "Total HTTP requests handled by the application", + ["method", "endpoint", "status_code"], +) +HTTP_REQUEST_DURATION_SECONDS = Histogram( + "http_request_duration_seconds", + "Duration of HTTP requests in seconds", + ["method", "endpoint", "status_code"], +) +HTTP_REQUESTS_IN_PROGRESS = Gauge( + "http_requests_in_progress", + "HTTP requests currently being processed", + ["method", "endpoint"], +) +ENDPOINT_CALLS_TOTAL = Counter( + "devops_info_endpoint_calls_total", + "Total calls to application endpoints", + ["endpoint"], +) +SYSTEM_INFO_COLLECTION_SECONDS = Histogram( + "devops_info_system_info_collection_seconds", + "Time spent collecting system information", +) + +# Setting up logging +logHandler = logging.StreamHandler() +formatter = jsonlogger.JsonFormatter( + fmt='%(asctime)s %(levelname)s %(name)s %(message)s', + datefmt='%Y-%m-%dT%H:%M:%S%z' +) +logHandler.setFormatter(formatter) +logger = logging.getLogger() +logger.addHandler(logHandler) +logger.setLevel(logging.INFO) + + +def ensure_parent_directory(file_path): + """Ensure the parent directory for a file exists.""" + os.makedirs(os.path.dirname(file_path), exist_ok=True) + + +def read_visits_count(): + """Read the visits counter from disk, defaulting to zero.""" + try: + with open(VISITS_FILE, "r", encoding="utf-8") as visits_file: + raw_value = visits_file.read().strip() + except FileNotFoundError: + return 0 + + if not raw_value: + return 0 + + try: + return int(raw_value) + except ValueError: + logger.warning("Invalid visits counter value, resetting to zero", extra={"file": VISITS_FILE}) + return 0 + + +def write_visits_count(count): + """Persist the visits counter using an atomic file replacement.""" + ensure_parent_directory(VISITS_FILE) + + with tempfile.NamedTemporaryFile( + "w", + encoding="utf-8", + dir=os.path.dirname(VISITS_FILE), + delete=False, + ) as temp_file: + temp_file.write(str(count)) + temp_file.flush() + os.fsync(temp_file.fileno()) + temp_path = temp_file.name + + os.replace(temp_path, VISITS_FILE) + + +def increment_visits_count(): + """Increment the visits counter in a thread-safe way.""" + with VISITS_LOCK: + count = read_visits_count() + 1 + write_visits_count(count) + return count + + +def load_app_config(): + """Load JSON configuration from disk if available.""" + try: + with open(CONFIG_FILE, "r", encoding="utf-8") as config_file: + return json.load(config_file) + except FileNotFoundError: + return {} + except json.JSONDecodeError: + logger.warning("Invalid JSON configuration file", extra={"file": CONFIG_FILE}) + return {} + + +def get_request_endpoint(): + """Return a normalized endpoint label with low cardinality.""" + if request.url_rule and request.url_rule.rule: + return request.url_rule.rule + if request.path == "/metrics": + return "/metrics" + return "unmatched" + + +@app.before_request +def log_request(): + endpoint = get_request_endpoint() + g.request_start_time = time.perf_counter() + g.metrics_endpoint = endpoint + HTTP_REQUESTS_IN_PROGRESS.labels( + method=request.method, + endpoint=endpoint, + ).inc() + logger.info("Request received", extra={ + 'method': request.method, + 'path': request.path, + 'ip': request.remote_addr + }) + +@app.after_request +def log_response(response): + endpoint = getattr(g, "metrics_endpoint", get_request_endpoint()) + HTTP_REQUESTS_TOTAL.labels( + method=request.method, + endpoint=endpoint, + status_code=str(response.status_code), + ).inc() + duration = time.perf_counter() - getattr(g, "request_start_time", time.perf_counter()) + HTTP_REQUEST_DURATION_SECONDS.labels( + method=request.method, + endpoint=endpoint, + status_code=str(response.status_code), + ).observe(duration) + HTTP_REQUESTS_IN_PROGRESS.labels( + method=request.method, + endpoint=endpoint, + ).dec() + logger.info("Response sent", extra={ + 'status': response.status_code, + 'method': request.method, + 'path': request.path + }) + return response + + +def get_system_info(): + """Collecting information about the system. + + Returns: + dict: System configuration + """ + with SYSTEM_INFO_COLLECTION_SECONDS.time(): + return { + "hostname": socket.gethostname(), + "platform": platform.system(), + "platform_version": platform.release(), + "architecture": platform.machine(), + "cpu_count": os.cpu_count() or 0, + "python_version": platform.python_version(), + } + + +def get_uptime(): + """Calculating the running time of the application. + + Returns: + dict: Uptime in seconds and human-readable format + """ + delta = datetime.now(timezone.utc) - START_TIME + seconds = int(delta.total_seconds()) + hours = seconds // 3600 + minutes = (seconds % 3600) // 60 + return {"seconds": seconds, "human": f"{hours} hours, {minutes} minutes"} + + +@app.route("/") +def index(): + """The main endpoint - Information about the service and the system.""" + client_ip = request.remote_addr + user_agent = request.headers.get("User-Agent", "Unknown") + endpoint = get_request_endpoint() + ENDPOINT_CALLS_TOTAL.labels(endpoint=endpoint).inc() + uptime = get_uptime() + system_info = get_system_info() + visits_count = increment_visits_count() + file_config = load_app_config() + + # Forming a response + response = { + "service": { + "name": "devops-info-service", + "version": "2.0.0", + "description": "DevOps course info service", + "framework": "Flask", + }, + "system": system_info, + "runtime": { + "uptime_seconds": uptime["seconds"], + "uptime_human": uptime["human"], + "current_time": datetime.now(timezone.utc).isoformat(), + "timezone": "UTC", + "visits_count": visits_count, + }, + "request": { + "client_ip": client_ip, + "user_agent": user_agent, + "method": request.method, + "path": request.path, + }, + "configuration": { + "file": file_config, + "environment": { + "APP_ENV": os.getenv("APP_ENV", "undefined"), + "LOG_LEVEL": os.getenv("LOG_LEVEL", "undefined"), + "FEATURE_GREETINGS": os.getenv("FEATURE_GREETINGS", "undefined"), + "CONFIG_FILE": CONFIG_FILE, + "DATA_DIR": DATA_DIR, + }, + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"}, + {"path": "/visits", "method": "GET", "description": "Visit counter"}, + {"path": "/metrics", "method": "GET", "description": "Prometheus metrics"}, + ], + } + return jsonify(response) + + +@app.route("/health") +def health(): + """Endpoint for health check.""" + ENDPOINT_CALLS_TOTAL.labels(endpoint=get_request_endpoint()).inc() + response = { + "status": "healthy", + "timestamp": datetime.now(timezone.utc).isoformat(), + "uptime_seconds": get_uptime()["seconds"], + } + logger.debug(f"Health check: {response}") + return jsonify(response), 200 + + +@app.route("/visits") +def visits(): + """Return the current visits counter without incrementing it.""" + ENDPOINT_CALLS_TOTAL.labels(endpoint=get_request_endpoint()).inc() + response = { + "visits": read_visits_count(), + "file": VISITS_FILE, + } + return jsonify(response), 200 + + +@app.route("/metrics") +def metrics(): + """Expose Prometheus metrics for scraping.""" + ENDPOINT_CALLS_TOTAL.labels(endpoint=get_request_endpoint()).inc() + return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST) + + +@app.errorhandler(404) +def not_found(error): + """Error handler 404.""" + logger.warning(f"404 Not Found: {request.path}") + return jsonify({"error": "Not Found", "message": "Endpoint does not exist"}), 404 + + +@app.errorhandler(500) +def internal_error(error): + """Error handler 500.""" + logger.error(f"500 Internal Server Error: {str(error)}") + return ( + jsonify( + { + "error": "Internal Server Error", + "message": "An unexpected error occurred", + } + ), + 500, + ) + + +if __name__ == "__main__": + logger.info(f"Starting DevOps Info Service on {HOST}:{PORT} (debug={DEBUG})") + app.run(host=HOST, port=PORT, debug=DEBUG) diff --git a/app_python/docs/LAB01.md b/app_python/docs/LAB01.md new file mode 100644 index 0000000000..90f920df57 --- /dev/null +++ b/app_python/docs/LAB01.md @@ -0,0 +1,271 @@ +# Lab 1 — DevOps Info Service: Web Application Development + +## Framework Selection + +### My Choice: Flask + +I selected **Flask** as the web framework for this DevOps Info Service. Here's why: + +**Comparison Table:** +| Criteria | Flask | FastAPI | Django | +|----------|-------|---------|--------| +| Learning Curve | Very low | Moderate | Steep | +| Development Speed | High | High | Medium | +| Built-in Features | Minimal | Moderate | Extensive | +| Auto-documentation | Requires extensions | Built-in (OpenAPI) | Requires extensions | +| Performance | Good | Excellent (async) | Good | +| Complexity | Low | Medium | High | +| **Choice for Lab 1** | **✓** | | | + +**Justification:** +Flask is a lightweight, minimalistic framework that perfectly suits our simple service with only two endpoints. For a DevOps monitoring tool foundation, we don't need the complexity of Django or the async capabilities of FastAPI yet. Flask allows rapid development with clean, understandable code, making it ideal for this educational project. Its simplicity aligns with the Unix philosophy of "do one thing well" - in this case, serve system information via HTTP. + +## Best Practices Applied + +### 1. Clean Code Organization +```python +# Clear imports grouping +import os +import socket +import platform +import logging +from datetime import datetime, timezone +from flask import Flask, jsonify, request + +# Descriptive function names with docstrings +def get_system_info(): + """Collecting information about the system. + Returns: + dict: System configuration + """ + return { + 'hostname': socket.gethostname(), + 'platform': platform.system(), + # ... more fields + } +``` + +**Importance:** Clean organization makes code maintainable, readable, and easier to debug. Following PEP 8 ensures consistency across Python projects. + +### 2. Comprehensive Error Handling +```python +@app.errorhandler(404) +def not_found(error): + """Error handler 404.""" + logger.warning(f"404 Not Found: {request.path}") + return jsonify({ + 'error': 'Not Found', + 'message': 'Endpoint does not exist' + }), 404 + +@app.errorhandler(500) +def internal_error(error): + """Error handler 500.""" + logger.error(f"500 Internal Server Error: {str(error)}") + return jsonify({ + 'error': 'Internal Server Error', + 'message': 'An unexpected error occurred' + }), 500 +``` + +**Importance:** Proper error handling prevents application crashes and provides meaningful feedback to API consumers. Each error type returns appropriate HTTP status codes and structured JSON responses. + +### 3. Structured Logging +```python +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger(__name__) + +logger.info(f'Starting DevOps Info Service on {HOST}:{PORT} (debug={DEBUG})') +logger.info(f"Request: {request.method} {request.path} from {client_ip}") +``` + +**Importance:** Logging provides visibility into application behavior, helps with debugging in production, and allows monitoring of API usage patterns. + +### 4. Configuration via Environment Variables +```python +HOST = os.getenv('HOST', '0.0.0.0') +PORT = int(os.getenv('PORT', 5000)) +DEBUG = os.getenv('DEBUG', 'False').lower() == 'true' +``` + +**Importance:** Following the 12-factor app methodology, configuration via environment variables makes the application portable across different environments (development, testing, production) without code changes. + +### 5. Version-Pinned Dependencies +```txt +# Web framework +Flask==3.1.0 + +# Virtual environment for python +python-dotenv==1.0.1 +``` + +**Importance:** Pinning exact versions ensures consistent behavior across all deployments and prevents "works on my machine" issues due to dependency version mismatches. + +### 6. Git Ignore for Development Artifacts +```gitignore +# Python +__pycache__/ +*.py[cod] +venv/ +*.log + +# IDE +.vscode/ +.idea/ + +# OS +.DS_Store +``` + +**Importance:** Prevents accidental commits of generated files, virtual environments, and sensitive data, keeping the repository clean and focused on source code. + +## API Documentation + +### Endpoint 1: `GET /` + +**Description:** Returns comprehensive service information, system details, runtime data, and request metadata. + +**Request:** +```bash +curl http://localhost:5000/ +``` + +**Response (example):** +```json +{ + "service": { + "name": "devops-info-service", + "version": "1.0.0", + "description": "DevOps course info service", + "framework": "Flask" + }, + "system": { + "hostname": "my-laptop", + "platform": "Linux", + "platform_version": "Ubuntu 24.04", + "architecture": "x86_64", + "cpu_count": 8, + "python_version": "3.13.1" + }, + "runtime": { + "uptime_seconds": 3600, + "uptime_human": "1 hour, 0 minutes", + "current_time": "2026-01-07T14:30:00.000Z", + "timezone": "UTC" + }, + "request": { + "client_ip": "127.0.0.1", + "user_agent": "curl/7.81.0", + "method": "GET", + "path": "/" + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"} + ] +} +``` + +### Endpoint 2: `GET /health` + +**Description:** Health check endpoint for monitoring system. Always returns HTTP 200 with service status. + +**Request:** +```bash +curl http://localhost:5000/health +``` + +**Response (example):** +```json +{ + "status": "healthy", + "timestamp": "2024-01-15T14:30:00.000Z", + "uptime_seconds": 3600 +} +``` + +### Testing Commands + +1. **Basic endpoint test:** + ```bash + curl http://localhost:5000/ + ``` + +2. **Health check test:** + ```bash + curl http://localhost:5000/health + ``` + +3. **Pretty-printed output:** + ```bash + curl http://localhost:5000/ | jq . + ``` + +4. **Custom configuration:** + ```bash + PORT=8080 python app.py + curl http://localhost:8080/health + ``` + +5. **Error simulation:** + ```bash + curl http://localhost:5000/nonexistent + # Should return 404 error + ``` + +## Testing Evidence + +### Main endpoint: +![Main Endpoint](screenshots/01-main-endpoint.png) + +### Health check: +![Health Check](screenshots/02-health-check.png) + +### Formatted output: +![Formatted output](screenshots/03-formatted-output.png) + + +## Challenges & Solutions + +### Challenge 1: Timezone-Aware Timestamps +**Problem:** `datetime.now()` without timezone creates naive datetime objects, which can cause issues with serialization and timezone calculations. + +**Solution:** Used `timezone.utc` consistently: +```python +from datetime import datetime, timezone +START_TIME = datetime.now(timezone.utc) +# ... +datetime.now(timezone.utc).isoformat() +``` + +### Challenge 2: Logging Configuration +**Problem:** Determining the appropriate log level and format for different types of messages. + +**Solution:** Configured logging with INFO level for normal operations, DEBUG for health checks, and WARNING/ERROR for error handlers: +```python +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) +logger.info(f"Request: {request.method} {request.path} from {client_ip}") +logger.debug(f"Health check: {response}") +logger.warning(f"404 Not Found: {request.path}") +``` + +### Challenge 3: CPU Count Handling +**Problem:** `os.cpu_count()` can return None on some systems or when the count cannot be determined. + +**Solution:** Added a fallback value: +```python +'cpu_count': os.cpu_count() or 0 +``` + +## GitHub Community +### Why starring repositories matters in open source: +Starring repositories serves as both a bookmarking tool for personal reference and a public endorsement that helps projects gain visibility, attracting more contributors and showing appreciation to maintainers for their work. + +### How following developers helps in team projects and professional growth: +Following developers enables you to stay updated on their projects and insights, fostering collaboration and knowledge sharing that accelerates team productivity and your own skill development in the tech community. \ No newline at end of file diff --git a/app_python/docs/LAB02.md b/app_python/docs/LAB02.md new file mode 100644 index 0000000000..aad9c97090 --- /dev/null +++ b/app_python/docs/LAB02.md @@ -0,0 +1,213 @@ +# Lab 2 — Containerization with Docker + +## Docker Best Practices Applied + +### 1. Multi-Stage Build +**Implementation:** +```dockerfile +FROM python:3.13-slim AS builder +# ... build stage with dependencies +FROM python:3.13-slim +COPY --from=builder /opt/venv /opt/venv +``` + +**Importance:** Separates the build environment from the runtime environment, reducing the final image size by excluding build tools and intermediate files. + +### 2. Non-Root User +**Implementation:** +```dockerfile +RUN groupadd -r appgroup && useradd -r -g appgroup appuser +USER appuser +``` + +**Importance:** Enhances security by following the principle of least privilege, minimizing potential damage if the container is compromised. + +### 3. Layer Caching Optimization +**Implementation:** +```dockerfile +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY . . +``` + +**Importance:** Docker caches layers. By copying requirements.txt first and installing dependencies, this layer is cached and only rebuilt when requirements change, speeding up subsequent builds. + +### 4. .dockerignore File +**Implementation:** Created a comprehensive `.dockerignore` file to exclude unnecessary files (development artifacts, IDE files, git, etc.). + +**Importance:** Reduces build context size, speeding up the build process and preventing sensitive or irrelevant files from being included. + +### 5. Specific Base Image Version +**Implementation:** `python:3.13-slim` (instead of `python:latest` or `python:3.13`) + +**Importance:** Ensures reproducible builds and avoids unexpected changes from base image updates. + +### 6. Clean Package Installation +**Implementation:** +```dockerfile +RUN pip install --no-cache-dir -r requirements.txt +``` + +**Importance:** The `--no-cache-dir` flag prevents pip from caching packages, reducing image size. + +### 7. System Dependency Cleanup +**Implementation:** +```dockerfile +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc \ + && rm -rf /var/lib/apt/lists/* +``` + +**Importance:** Removes the package lists after installation, reducing image size and keeping the image clean. + +### 8. Virtual Environment Isolation +**Implementation:** +```dockerfile +RUN python -m venv /opt/venv +ENV PATH="/opt/venv/bin:$PATH" +``` + +**Importance:** Isolates application dependencies from the system Python, avoiding conflicts and making the environment reproducible. + +## Image Information & Decisions + +### Base Image Choice +**Selected:** `python:3.13-slim` + +**Justification:** +- **slim variant** provides a minimal Python runtime without unnesecary extra tools +- **Specific version (3.13)** ensures reproducibility and avoids breaking changes from future updates +- **Alternative considered:** `python:3.13-alpine` (about 45MB) was rejected due to potential compatibility issues with some Python packages that require compiled binaries. + +### Final Image Size +- **Final image size:** ~199MB + +**Assessment:** The image size is reasonable for a Python application. The multi-stage build helps keep it minimal by excluding build tools. Further reduction could be achieved by using Alpine, but at the cost of potential compatibility issues. + +### Layer Structure +The layer structure (from bottom to top): +1. **Base image layer:** `python:3.13-slim` +2. **System dependencies layer:** Installs gcc (builder stage) +3. **Python dependencies layer:** Creates virtual environment and installs packages (cached separately) +4. **Application code layer:** Copies the rest of the application +5. **Configuration layer:** Sets permissions, user, environment variables, and command + +### Optimization Choices Made +1. **Multi-stage build:** Separates build and runtime, removing build tools from final image. +2. **Dependency layer caching:** Requirements are installed in a separate layer that caches well. +3. **Cleanup:** Removal of apt lists and pip cache. +4. **Non-root user:** Added for security without significant overhead. +5. **Virtual environment:** Ensures dependency isolation and easier path management. + +## Build & Run Process + +### Complete Terminal Output from Build Process +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 ● λ docker build -t devops-info-service:python . +[+] Building 2.1s (17/17) FINISHED docker:default + => [internal] load build definition from Dockerfile 0.0s + => => transferring dockerfile: 1.41kB 0.0s + => [internal] load metadata for docker.io/library/python:3.13-slim 1.9s + => [auth] library/python:pull token for registry-1.docker.io 0.0s + => [internal] load .dockerignore 0.0s + => => transferring context: 321B 0.0s + => [internal] load build context 0.0s + => => transferring context: 63B 0.0s + => [builder 1/6] FROM docker.io/library/python:3.13-slim@sha256:51e1a0a317fdb6e170dc791bbeae63fac5272c82f43958ef74a34e170c6f8b18 0.0s + => => resolve docker.io/library/python:3.13-slim@sha256:51e1a0a317fdb6e170dc791bbeae63fac5272c82f43958ef74a34e170c6f8b18 0.0s + => CACHED [stage-1 2/6] RUN groupadd -r appgroup && useradd -r -g appgroup appuser 0.0s + => CACHED [stage-1 3/6] WORKDIR /app 0.0s + => CACHED [builder 2/6] RUN apt-get update && apt-get install -y --no-install-recommends gcc && rm -rf /var/lib/apt/lists/* 0.0s + => CACHED [builder 3/6] WORKDIR /app 0.0s + => CACHED [builder 4/6] RUN python -m venv /opt/venv 0.0s + => CACHED [builder 5/6] COPY requirements.txt . 0.0s + => CACHED [builder 6/6] RUN pip install --no-cache-dir --upgrade pip && pip install --no-cache-dir -r requirements.txt 0.0s + => CACHED [stage-1 4/6] COPY --from=builder /opt/venv /opt/venv 0.0s + => CACHED [stage-1 5/6] COPY . . 0.0s + => CACHED [stage-1 6/6] RUN chown -R appuser:appgroup /app && chmod -R 755 /app 0.0s + => exporting to image 0.1s + => => exporting layers 0.0s + => => exporting manifest sha256:d9c4d5bbff6c71a63a4664b6176a7cf8d5738ea116827f910b356d290148a06f 0.0s + => => exporting config sha256:0cea5c6e8fea36e6da7112c67af628d9a5ecaca41edfd9f12b32a6ebf2f6c9b2 0.0s + => => exporting attestation manifest sha256:45c2bd60bc20c64827da237a0a245707051321a55ecbac6b03d1001102cc86d2 0.0s + => => exporting manifest list sha256:4b08b6e2f06333a4d7781a83bcebcdb3303c99ef310af40ae3e0e85e2a020d3e 0.0s + => => naming to docker.io/library/devops-info-service:python 0.0s + => => unpacking to docker.io/library/devops-info-service:python +``` + +### Terminal Output Showing Container Running +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 ● λ docker run -d --name devops-python -p 5000:5000 devops-info-service:python +234bff345b8f2c930681218fd9536b405c131b375a4d382a0b28a4f77d067b2c + +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 ● λ docker logs devops-python +2026-01-31 18:45:04,632 - __main__ - INFO - Starting DevOps Info Service on 0.0.0.0:5000 (debug=False) + * Serving Flask app 'app' + * Debug mode: off +2026-01-31 18:45:04,639 - 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-01-31 18:45:04,639 - werkzeug - INFO - Press CTRL+C to quit +``` + +### Terminal Output from Testing Endpoints +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 ● λ curl http://localhost:5000/ +{"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.18.0"},"runtime":{"current_time":"2026-01-31T18:45:48.101588+00:00","timezone":"UTC","uptime_human":"0 hours, 0 minutes","uptime_seconds":43},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":12,"hostname":"234bff345b8f","platform":"Linux","platform_version":"6.18.3-arch1-1","python_version":"3.13.11"}} + +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 ● λ curl http://localhost:5000/health +{"status":"healthy","timestamp":"2026-01-31T18:45:54.984116+00:00","uptime_seconds":50} +``` + +### Docker Hub Repository URL +**URL:** https://hub.docker.com/repository/docker/s3rap1s/devops-info-service/general + +## Technical Analysis + +### Why Does Your Dockerfile Work the Way It Does? +The Dockerfile uses a multi-stage build to separate concerns: +1. **Builder stage:** Installs system dependencies and Python packages in a virtual environment. +2. **Runtime stage:** Copies only the virtual environment and application code, then sets up a secure non-root user. + +This approach ensures that the final image contains only what's necessary to run the application, improving security and reducing size. + +### What Would Happen If You Changed the Layer Order? +If the layer order were changed, then every time any file in the project changes, the `COPY` layer would be invalidated, causing the `RUN` layer to also be invalidated (since Docker caches layers based on the previous layer's hash). This would result in a full reinstallation of dependencies on every code change, significantly slowing down builds. + +### What Security Considerations Did You Implement? +1. **Non-root user:** The application runs as a dedicated user with minimal privileges. +2. **Minimal base image:** The `slim` variant reduces attack surface. +3. **Virtual environment isolation:** Prevents dependency conflicts and limits access. +4. **No unnecessary services:** Only the Python application runs in the container. +5. **Cleanup of package lists:** Removes sensitive data and reduces image size. +6. **Explicit port exposure:** Only port 5000 is exposed. + +### How Does .dockerignore Improve Your Build? +The `.dockerignore` file excludes: +- Development artifacts (`.git`, `__pycache__`, `.venv`) +- IDE files (`.vscode`, `.idea`) +- Logs and temporary files +- Documentation and tests (not needed at runtime) + +This reduces the build context sent to the Docker daemon, resulting in: +- **Faster build** - smaller context to transfer +- **Smaller image sizes** - unnecessary files aren't included +- **Improved security** - sensitive files like secrets aren't accidentally included + +## Challenges & Solutions + +### Challenge: Port Configuration Inside Container +**Problem:** The application inside the container was binding to `localhost`, making it inaccessible from the host. + +**Solution:** Set the `HOST` environment variable to `0.0.0.0` in the Dockerfile to bind to all interfaces: +```dockerfile +ENV HOST=0.0.0.0 +``` + +## What I Learned + +1. **Layer caching** is crucial for efficient Docker builds +2. **Security** must be considered from the start +3. **`.dockerignore`** is as important as `.gitignore` for Docker projects, affecting both performance and security +4. **Reproducibility** requires pinning specific versions of base images and dependencies diff --git a/app_python/docs/LAB03.md b/app_python/docs/LAB03.md new file mode 100644 index 0000000000..8201a6fa31 --- /dev/null +++ b/app_python/docs/LAB03.md @@ -0,0 +1,200 @@ +# Lab 3 — Continuous Integration (CI/CD) + +## Overview + +### Testing Framework Choice +I selected **pytest** as the testing framework for the following reasons: + +1. **Simple and intuitive syntax** - easy to write and read tests +2. **Rich feature set** - fixtures, parameterization, and plugins +3. **Active community** - extensive documentation and support +4. **CI/CD integration** - seamless integration with GitHub Actions + +### Versioning Strategy +**Calendar Versioning (CalVer)** in the format `YYYY.MM.MICRO` + +**Why CalVer was chosen:** +1. **DevOps service** with frequent updates and rare breaking changes +2. **Stable API** - backward compatible changes only +3. **Date clarity** - immediately shows image freshness +4. **Flexibility** - micro version allows multiple builds per day + +### CI Workflow Triggers +- **Push** to branches: master, lab03 (only when app_python/ files change) +- **Pull Request** to branches: master (for code review) +- **Path filters** - workflow only runs when relevant files are modified + +## Workflow Evidence + +### Successful Workflow Run +[Link to successful workflow run](https://github.com/s3rap1s/DevOps-Core-Course/actions/runs/21864360584/) + +### Terminal Output from Local Testing +```bash +(venv) s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab03 ● ● λ pytest --cov=app --cov-report=term-missing -v +======================================================================================================================== test session starts ======================================================================================================================== +platform linux -- Python 3.14.2, pytest-8.1.1, pluggy-1.6.0 -- /home/s3rap1s/devops/DevOps-Core-Course/app_python/venv/bin/python3 +cachedir: .pytest_cache +rootdir: /home/s3rap1s/devops/DevOps-Core-Course/app_python +plugins: cov-5.0.0 +collected 8 items + +tests/test_app.py::test_get_system_info PASSED [ 12%] +tests/test_app.py::test_get_uptime PASSED [ 25%] +tests/test_app.py::test_main_endpoint PASSED [ 37%] +tests/test_app.py::test_health_endpoint PASSED [ 50%] +tests/test_app.py::test_404_error PASSED [ 62%] +tests/test_app.py::test_different_user_agent PASSED [ 75%] +tests/test_app.py::test_json_structure_types PASSED [ 87%] +tests/test_app.py::test_health_response_structure PASSED [100%] + +---------- coverage: platform linux, python 3.14.2-final-0 ----------- +Name Stmts Miss Cover Missing +-------------------------------------- +app.py 44 4 91% 118-119, 131-132 +-------------------------------------- +TOTAL 44 4 91% + + +========================================================================================================================= 8 passed in 0.09s ========================================================================================================================= +``` + +### Docker Hub Images +- **Latest:** `s3rap1s/devops-info-service:latest` +- **Date-based:** `s3rap1s/devops-info-service:2026.02.10` +- **CalVer:** `username/devops-info-service:2026.02.3` + +**Docker Hub URL:** https://hub.docker.com/r/s3rap1s/devops-info-service + +## Best Practices Implemented + +### 1. Dependency Caching +- **Pip caching:** Saves ~40 seconds per workflow run +- **Docker layer caching:** Speeds up image builds by ~67% +- **Cache key strategy:** Based on dependency file hash for maximum efficiency + +### 2. Security Scanning with Snyk +- Integrated vulnerability scanning for Python dependencies +- Configured to fail only on "high" severity vulnerabilities +- Automated scanning in every CI run + +### 3. Path Filters +- Workflow only triggers when app_python/ files change +- Prevents unnecessary CI runs for documentation or other app changes +- Saves CI/CD minutes and resources + +### 4. Job Dependencies +- Docker build job depends on successful test completion +- Prevents pushing broken code to Docker Hub +- Ensures only tested code reaches production + +### 5. Docker Layer Caching +- Caches Docker build layers between workflow runs +- Significant performance improvement for multi-stage builds +- Uses GitHub Actions cache for persistence + +### 6. Multiple Docker Tags +- `latest` - for production deployments +- `YYYY.MM.DD` - specific date builds +- `YYYY.MM.MICRO` - CalVer versioning + +### 7. Fail Fast Strategy +- Stops workflow on first linting or testing failure +- Provides immediate feedback to developers +- Reduces resource consumption on failed builds + +## Key Decisions + +### Versioning Strategy: CalVer +**Why CalVer over SemVer?** +1. **Infrastructure service** - frequent updates without breaking API changes +2. **Time-based relevance** - date indicates service freshness +3. **Simpler management** - no need for manual version bumping +4. **Industry practice** - common for DevOps and infrastructure tools + +### Workflow Trigger Configuration +**Why these triggers?** +1. **Push to master** - Automate production deployments +2. **Pull requests** - Ensure code quality before merging +3. **Path filters** - Optimize CI resource usage +4. **Branch-specific logic** - Different behavior for feature branches vs main + +## Test Coverage Analysis + +### Current Coverage: 91% + +**What's covered:** +- All API endpoints (`GET /` and `GET /health`) +- Error handling (404 responses) +- JSON structure validation +- Data type checking +- Function-level unit tests + +**Coverage goal:** Maintain >85% coverage threshold + +## Challenges & Solutions + +### Challenge 1: Snyk Integration Complexity +**Problem:** Snyk dependenicy for python failed during installation +**Solution:** Used official Docker-container from Snyk, which has all needed instruments and has seamless connection in GitHub + + +## Performance Metrics + +### Workflow Execution Time +| Stage | Without Caching | With Caching | Improvement | +|-------|----------------|--------------|-------------| +| Dependency Installation | 45s | 5s | 89% | +| Docker Build | 60s | 20s | 67% | +| Total Workflow | 2m 30s | 1m 10s | 53% | + +### Resource Optimization +- **CI minutes saved:** ~50% per workflow run +- **Storage optimization:** Docker layer cache reduces image size +- **Network efficiency:** Cached dependencies reduce download time + +## Security Considerations + +### Snyk Scanning Results +**Configuration:** +- Severity threshold: High +- Scan type: Python dependencies +- Action on vulnerabilities: Warning only (doesn't fail build) + +**Findings:** +- No high severity vulnerabilities detected +- Regular monitoring ensures security updates + +### Docker Security Best Practices +1. **Non-root user** in Dockerfile +2. **Minimal base image** (python:3.13-slim) +3. **Regular vulnerability scanning** +4. **Immutable tags** for production deployments + +## Integration Points + +### Code Quality Tools +- **flake8** - Code linting and style checking +- **black** - Automatic code formatting +- **pytest** - Comprehensive testing framework + +### External Services +- **GitHub Actions** - CI/CD platform +- **Docker Hub** - Container registry +- **Snyk** - Security scanning +- **Git** - Version control and tagging + +### Screenshots +![CI/CD Workflow Success](screenshots/04-ci-success.png) +![Test Coverage Report](screenshots/05-test-coverage.png) + +## Conclusion + +This CI/CD implementation provides: +- **Automated testing** with 91% code coverage +- **Security scanning** with Snyk integration +- **Efficient Docker builds** with layer caching +- **Meaningful versioning** with CalVer strategy +- **Resource optimization** through dependency caching + +The pipeline ensures code quality, security, and reliable deployments while optimizing CI resource usage and providing clear feedback to developers. 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..c374142b86 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..ae97ae06f3 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..0c99336f5c Binary files /dev/null and b/app_python/docs/screenshots/03-formatted-output.png differ diff --git a/app_python/docs/screenshots/04-ci-success.png b/app_python/docs/screenshots/04-ci-success.png new file mode 100644 index 0000000000..d4f73eb7e9 Binary files /dev/null and b/app_python/docs/screenshots/04-ci-success.png differ diff --git a/app_python/docs/screenshots/05-test-coverage.png b/app_python/docs/screenshots/05-test-coverage.png new file mode 100644 index 0000000000..a1c7a63cf5 Binary files /dev/null and b/app_python/docs/screenshots/05-test-coverage.png differ diff --git a/app_python/requirements.txt b/app_python/requirements.txt new file mode 100644 index 0000000000..7bd58ef8fb --- /dev/null +++ b/app_python/requirements.txt @@ -0,0 +1,14 @@ +# Web framework +Flask==3.1.0 + +# Testing +pytest==8.1.1 +pytest-cov==5.0.0 +requests==2.31.0 + +# Logging framework +python-json-logger==2.0.7 +prometheus-client==0.23.1 + +# Virtual environment for python +python-dotenv==1.0.1 diff --git a/app_python/tests/__init__.py b/app_python/tests/__init__.py new file mode 100644 index 0000000000..be62617d4e --- /dev/null +++ b/app_python/tests/__init__.py @@ -0,0 +1 @@ +# Unit tests (Lab 3) diff --git a/app_python/tests/test_app.py b/app_python/tests/test_app.py new file mode 100644 index 0000000000..ccc88ee490 --- /dev/null +++ b/app_python/tests/test_app.py @@ -0,0 +1,254 @@ +import pytest +import sys +import os +import json + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) +import app as app_module + +app = app_module.app + + +@pytest.fixture +def client(tmp_path, monkeypatch): + """Fixture for test client Flask""" + visits_file = tmp_path / "visits" + config_file = tmp_path / "config.json" + config_file.write_text( + json.dumps( + { + "application_name": "test-devops-service", + "environment": "test", + "settings": { + "featureGreeting": True, + "maxVisitsDisplay": 10, + }, + } + ), + encoding="utf-8", + ) + monkeypatch.setattr(app_module, "DATA_DIR", str(tmp_path)) + monkeypatch.setattr(app_module, "VISITS_FILE", str(visits_file)) + monkeypatch.setattr(app_module, "CONFIG_FILE", str(config_file)) + with app.test_client() as client: + yield client + + +def test_get_system_info(): + """Test of get_system_info()""" + from app import get_system_info + + info = get_system_info() + + assert isinstance(info, dict) + assert "hostname" in info + assert "platform" in info + assert "python_version" in info + assert isinstance(info["cpu_count"], int) + + +def test_get_uptime(): + """Test of get_uptime()""" + from app import get_uptime + + uptime = get_uptime() + + assert isinstance(uptime, dict) + assert "seconds" in uptime + assert "human" in uptime + assert isinstance(uptime["seconds"], int) + assert isinstance(uptime["human"], str) + + +def test_main_endpoint(client): + """Test of main endpoint GET /""" + response = client.get("/") + + # Status check + assert response.status_code == 200 + + # Json structure test + data = response.get_json() + + # Service structure test + assert "service" in data + assert data["service"]["name"] == "devops-info-service" + assert data["service"]["version"] == "2.0.0" + assert data["service"]["framework"] == "Flask" + + # System structure test + assert "system" in data + assert all( + key in data["system"] + for key in [ + "hostname", + "platform", + "platform_version", + "architecture", + "cpu_count", + "python_version", + ] + ) + + # Time structure test + assert "runtime" in data + assert "uptime_seconds" in data["runtime"] + assert "current_time" in data["runtime"] + assert data["runtime"]["timezone"] == "UTC" + assert data["runtime"]["visits_count"] == 1 + + # Request structure test + assert "request" in data + assert "client_ip" in data["request"] + assert "method" in data["request"] + assert data["request"]["method"] == "GET" + + assert "configuration" in data + assert data["configuration"]["file"]["application_name"] == "test-devops-service" + assert data["configuration"]["environment"]["CONFIG_FILE"].endswith("config.json") + + # Endpoints structure test + assert "endpoints" in data + assert isinstance(data["endpoints"], list) + assert len(data["endpoints"]) >= 3 + + +def test_health_endpoint(client): + """Test of health endpoint GET /health""" + response = client.get("/health") + + # Status check + assert response.status_code == 200 + + # Json structure test + data = response.get_json() + + assert "status" in data + assert data["status"] == "healthy" + assert "timestamp" in data + assert "uptime_seconds" in data + assert isinstance(data["uptime_seconds"], int) + + +def test_404_error(client): + """404 error handling test""" + response = client.get("/nonexistent") + + assert response.status_code == 404 + + data = response.get_json() + assert "error" in data + assert "message" in data + assert data["error"] == "Not Found" + + +def test_different_user_agent(client): + """Test with different User-Agent headers.""" + headers = {"User-Agent": "Test-Agent/1.0"} + response = client.get("/", headers=headers) + + assert response.status_code == 200 + data = response.get_json() + assert data["request"]["user_agent"] == "Test-Agent/1.0" + + +def test_json_structure_types(client): + """Checking the data types in the JSON response""" + response = client.get("/") + data = response.get_json() + + # Type check in service + assert isinstance(data["service"]["name"], str) + assert isinstance(data["service"]["version"], str) + assert isinstance(data["service"]["description"], str) + + # Type check in system + assert isinstance(data["system"]["hostname"], str) + assert isinstance(data["system"]["cpu_count"], int) + assert isinstance(data["system"]["python_version"], str) + + # Type check in runtime + assert isinstance(data["runtime"]["uptime_seconds"], int) + assert isinstance(data["runtime"]["current_time"], str) + + +def test_health_response_structure(client): + """Detailed verification of the health endpoint structure""" + response = client.get("/health") + data = response.get_json() + + # Checking all required fields + required_fields = ["status", "timestamp", "uptime_seconds"] + for field in required_fields: + assert field in data + + # Checking the status value + assert data["status"] == "healthy" + + # Checking the timestamp format + from datetime import datetime + + try: + datetime.fromisoformat(data["timestamp"].replace("Z", "+00:00")) + timestamp_valid = True + except ValueError: + timestamp_valid = False + assert timestamp_valid + + +def test_metrics_endpoint(client): + """Metrics endpoint exposes Prometheus metrics in text format.""" + client.get("/") + client.get("/health") + + response = client.get("/metrics") + + assert response.status_code == 200 + assert response.mimetype == "text/plain" + + metrics_output = response.get_data(as_text=True) + metric_lines = metrics_output.splitlines() + + assert "http_requests_total" in metrics_output + assert any( + line.startswith("http_requests_total{") + and 'endpoint="/"' in line + and 'method="GET"' in line + and 'status_code="200"' in line + for line in metric_lines + ) + assert any( + line.startswith("http_requests_total{") + and 'endpoint="/health"' in line + and 'method="GET"' in line + and 'status_code="200"' in line + for line in metric_lines + ) + assert "http_request_duration_seconds_bucket" in metrics_output + assert any( + line.startswith("http_requests_in_progress{") + and 'endpoint="/metrics"' in line + and 'method="GET"' in line + for line in metric_lines + ) + assert "devops_info_endpoint_calls_total" in metrics_output + assert "devops_info_system_info_collection_seconds_bucket" in metrics_output + + +def test_visits_endpoint_and_persistence(client): + """The root endpoint increments visits and /visits returns the stored counter.""" + first_response = client.get("/") + second_response = client.get("/") + visits_response = client.get("/visits") + + assert first_response.status_code == 200 + assert second_response.status_code == 200 + assert visits_response.status_code == 200 + + assert first_response.get_json()["runtime"]["visits_count"] == 1 + assert second_response.get_json()["runtime"]["visits_count"] == 2 + assert visits_response.get_json()["visits"] == 2 + assert os.path.exists(app_module.VISITS_FILE) + + with open(app_module.VISITS_FILE, "r", encoding="utf-8") as visits_file: + assert visits_file.read().strip() == "2" diff --git a/docs/LAB04.md b/docs/LAB04.md new file mode 100644 index 0000000000..3ad7dc822b --- /dev/null +++ b/docs/LAB04.md @@ -0,0 +1,392 @@ +# Lab 4 — Infrastructure as Code (Terraform & Pulumi) + +## Cloud Provider & Infrastructure + +### Choice of Environment +I chose to use a **local virtual machine** as my "cloud provider" for this lab. The VM runs on VirtualBox on my Archlinux host. This decision was made to avoid any cloud costs, simplify the setup, and have full control over the infrastructure. The VM will also be used in Lab 5 (Ansible). + +### VM Specifications +- **Virtualization Software:** VirtualBox 7.2.6 +- **Guest OS:** Ubuntu Server 24.04 LTS +- **Resources:** 2 GB RAM, 25 GB dynamic disk +- **Network:** NAT with port forwarding (host port 2222 → guest port 22) +- **SSH Access:** `ssh devops@localhost -p 2222` + +The VM was created manually following the lab instructions, and its configuration is documented here to represent the infrastructure managed by IaC tools. + + +## Terraform Implementation + +### Terraform Version +``` +Terraform v1.14.5 on linux_amd64 +``` + +### Project Structure +``` +terraform/ +├── main.tf # Main resources (local files) +├── variables.tf # Input variables (empty for now) +├── outputs.tf # Output definitions +└── .gitignore # Ignore state files +``` + +### Key Configuration Decisions +Since the infrastructure is a local VM, we cannot manage it directly with Terraform's cloud providers. Instead, we used the `local` provider to create descriptive files that represent the infrastructure. This demonstrates the concept of Infrastructure as Code – defining infrastructure in code, even if the actual resources are provisioned outside of Terraform. + +**main.tf**: +```hcl +resource "local_file" "vm_info" { + content = <<-EOT + This file represents the infrastructure created by Terraform for Lab 4. + VM Name: devops-vm + SSH User: devops + SSH Port (Host): 2222 + OS: Ubuntu Server 24.04 LTS + Managed by: Terraform + Created at: ${timestamp()} + EOT + filename = "${path.module}/vm_terraform_info.txt" +} + +resource "local_file" "ansible_inventory" { + content = <<-EOT + [devops_vm] + devops-vm ansible_host=localhost ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_rsa + EOT + filename = "${path.module}/../ansible_inventory.ini" +} + +output "vm_info_file_created" { + value = local_file.vm_info.filename +} + +output "ansible_inventory_file" { + value = local_file.ansible_inventory.filename +} +``` + +**outputs.tf**: +```hcl +output "vm_info_file" { + value = local_file.vm_info.filename +} + +output "ansible_inventory_file" { + value = local_file.ansible_inventory.filename +} + +output "creation_timestamp" { + value = timestamp() +} +``` + +### Applying Infrastructure +```bash +devops@devops:~/devops_lab/terraform$ terraform init +Initializing the backend... +Initializing provider plugins... +- Finding latest version of hashicorp/local... +- Installing hashicorp/local v2.5.1... +- Installed hashicorp/local v2.5.1 (unauthenticated) +Terraform has created a lock file .terraform.lock.hcl to record the provider +selections it made above. Include this file in your version control repository +so that Terraform can guarantee to make the same selections by default when +you run "terraform init" in the future. + +╷ +│ Warning: Incomplete lock file information for providers +│ +│ Due to your customized provider installation methods, Terraform was forced to calculate lock file checksums locally for the following providers: +│ - hashicorp/local +│ +│ The current .terraform.lock.hcl file only includes checksums for linux_amd64, so Terraform running on another platform will fail to install these providers. +│ +│ To calculate additional checksums for another platform, run: +│ terraform providers lock -platform=linux_amd64 +│ (where linux_amd64 is the platform to generate) +╵ +Terraform has been successfully initialized! + +You may now begin working with Terraform. Try running "terraform plan" to see +any changes that are required for your infrastructure. All Terraform commands +should now work. + +If you ever set or change modules or backend configuration for Terraform, +rerun this command to reinitialize your working directory. If you forget, other +commands will detect it and remind you to do so if necessary. +devops@devops:~/devops_lab/terraform$ terraform plan + +Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + + create + +Terraform will perform the following actions: + + # local_file.ansible_inventory will be created + + resource "local_file" "ansible_inventory" { + + content = <<-EOT + [devops_vm] + devops-vm ansible_host=localhost ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_rsa + EOT + + content_base64sha256 = (known after apply) + + content_base64sha512 = (known after apply) + + content_md5 = (known after apply) + + content_sha1 = (known after apply) + + content_sha256 = (known after apply) + + content_sha512 = (known after apply) + + directory_permission = "0777" + + file_permission = "0777" + + filename = "./../ansible_inventory.ini" + + id = (known after apply) + } + + # local_file.vm_info will be created + + resource "local_file" "vm_info" { + + content = (known after apply) + + content_base64sha256 = (known after apply) + + content_base64sha512 = (known after apply) + + content_md5 = (known after apply) + + content_sha1 = (known after apply) + + content_sha256 = (known after apply) + + content_sha512 = (known after apply) + + directory_permission = "0777" + + file_permission = "0777" + + filename = "./vm_terraform_info.txt" + + id = (known after apply) + } + +Plan: 2 to add, 0 to change, 0 to destroy. + +Changes to Outputs: + + ansible_inventory_file = "./../ansible_inventory.ini" + + vm_info_file_created = "./vm_terraform_info.txt" + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now. +devops@devops:~/devops_lab/terraform$ terraform apply -auto-approve + +Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + + create + +Terraform will perform the following actions: + + # local_file.ansible_inventory will be created + + resource "local_file" "ansible_inventory" { + + content = <<-EOT + [devops_vm] + devops-vm ansible_host=localhost ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_rsa + EOT + + content_base64sha256 = (known after apply) + + content_base64sha512 = (known after apply) + + content_md5 = (known after apply) + + content_sha1 = (known after apply) + + content_sha256 = (known after apply) + + content_sha512 = (known after apply) + + directory_permission = "0777" + + file_permission = "0777" + + filename = "./../ansible_inventory.ini" + + id = (known after apply) + } + + # local_file.vm_info will be created + + resource "local_file" "vm_info" { + + content = (known after apply) + + content_base64sha256 = (known after apply) + + content_base64sha512 = (known after apply) + + content_md5 = (known after apply) + + content_sha1 = (known after apply) + + content_sha256 = (known after apply) + + content_sha512 = (known after apply) + + directory_permission = "0777" + + file_permission = "0777" + + filename = "./vm_terraform_info.txt" + + id = (known after apply) + } + +Plan: 2 to add, 0 to change, 0 to destroy. + +Changes to Outputs: + + ansible_inventory_file = "./../ansible_inventory.ini" + + vm_info_file_created = "./vm_terraform_info.txt" +local_file.ansible_inventory: Creating... +local_file.vm_info: Creating... +local_file.ansible_inventory: Creation complete after 0s [id=d2dd8bfe83944cd4c03041974ec1e5b7b986a264] +local_file.vm_info: Creation complete after 0s [id=3e82a1249bfd3da17b5906b4f457c664214a1651] + +Apply complete! Resources: 2 added, 0 changed, 0 destroyed. + +Outputs: + +ansible_inventory_file = "./../ansible_inventory.ini" +vm_info_file_created = "./vm_terraform_info.txt" +``` + +### Verification +Both files were created successfully: +```bash +devops@devops:~/devops_lab/terraform$ cat vm_terraform_info.txt +This file represents the infrastructure created by Terraform for Lab 4. +VM Name: devops-vm +SSH User: devops +SSH Port (Host): 2222 +OS: Ubuntu Server 24.04 LTS +Managed by: Terraform +Created at: 2026-02-18T13:50:07Z +devops@devops:~/devops_lab/terraform$ cat ../ansible_inventory.ini +[devops_vm] +devops-vm ansible_host=localhost ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_rsa +``` + +## Pulumi Implementation + +### Pulumi Version & Language +- **Pulumi version:** 3.221.0 +- **Language:** Python 3.12.3 +- **State backend:** Local (`pulumi login --local`) + +### Project Structure +``` +pulumi/ +├── __main__.py # Infrastructure code +├── requirements.txt # Python dependencies +├── Pulumi.yaml # Project metadata +└── Pulumi.dev.yaml # Stack configuration (local) +``` + +### Code Implementation +The Pulumi program creates the same two files using plain Python code, demonstrating the imperative approach. + +**__main__.py**: +```python +import pulumi +from datetime import datetime + +vm_info_content = f""" +This file represents the infrastructure created by Pulumi for Lab 4. +VM Name: devops-vm +SSH User: devops +SSH Port (Host): 2222 +OS: Ubuntu Server 24.04 LTS +Managed by: Pulumi (Python) +Created at: {datetime.now().isoformat()} +""" + +with open('./vm_pulumi_info.txt', 'w') as f: + f.write(vm_info_content) + +pulumi.export('vm_info_file', './vm_pulumi_info.txt') +pulumi.export('message', 'Pulumi infrastructure applied successfully!') +pulumi.export('timestamp', datetime.now().isoformat()) + +inventory_lines = [ + "[devops_vm]", + "devops-vm ansible_host=localhost ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_rsa" +] +inventory_content = "\n".join(inventory_lines) +with open('../pulumi_ansible_inventory.ini', 'w') as f: + f.write(inventory_content) + +pulumi.export('ansible_inventory', '../pulumi_ansible_inventory.ini') +``` + +### Applying Infrastructure +```bash +(venv) devops@devops:~/devops_lab/pulumi$ pulumi up -y +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 update (dev): + Type Name Plan + + pulumi:pulumi:Stack project-dev create + +Outputs: + ansible_inventory: "../pulumi_ansible_inventory.ini" + message : "Pulumi infrastructure applied successfully!" + timestamp : "2026-02-18T13:58:26.931155" + vm_info_file : "./vm_pulumi_info.txt" + +Resources: + + 1 to create + +Updating (dev): + Type Name Status + + pulumi:pulumi:Stack project-dev created (0.00s) + +Outputs: + ansible_inventory: "../pulumi_ansible_inventory.ini" + message : "Pulumi infrastructure applied successfully!" + timestamp : "2026-02-18T13:58:27.238400" + vm_info_file : "./vm_pulumi_info.txt" + +Resources: + + 1 created + +Duration: 1s +``` + +### Verification +Files were created and contain the expected data: +```bash +(venv) devops@devops:~/devops_lab/pulumi$ cat vm_pulumi_info.txt + +This file represents the infrastructure created by Pulumi for Lab 4. +VM Name: devops-vm +SSH User: devops +SSH Port (Host): 2222 +OS: Ubuntu Server 24.04 LTS +Managed by: Pulumi (Python) +Created at: 2026-02-18T13:58:27.238285 +(venv) devops@devops:~/devops_lab/pulumi$ cat ../pulumi_ansible_inventory.ini +[devops_vm] +devops-vm ansible_host=localhost ansible_port=2222 ansible_user=devops ansible_ssh_private_key_file=~/.ssh/id_rsa +``` + + +## Terraform vs Pulumi Comparison + +| Aspect | Terraform | Pulumi | +|--------|-----------|--------| +| **Ease of Learning** | HCL is simple and declarative, easy to pick up even without programming background | Requires knowledge of a programming language (Python/TypeScript/Go), but does not require any new language if developer already familiar with any | +| **Code Readability** | Configuration is clean and resource-focused | The code is imperative and can mix infrastructure logic with application logic. For simple resources, it's still readable, but complex logic may obscure the infrastructure intent | +| **Debugging** | Error messages are generally clear, but debugging complex interpolation can be tricky | Full language debugging makes troubleshooting much easier | +| **Documentation** | Terraform Registry has well-structured documentation | Pulumi Registry also has good docs, but often you need to know the underlying cloud provider API as well | +| **Use Case** | Best for pure infrastructure provisioning, especially in team environments where a declarative approach is preferred | Ideal when infrastructure needs to be tightly integrated with application code, or when you need complex logic (loops, conditionals, external libraries) | + +**My Personal Preference:** +For this simple task, both tools worked well. However, I found Pulumi more intuitive because I am comfortable with imperative languages + + +## Lab 5 Preparation & Cleanup + +### Keeping the VM for Lab 5 +- **I am keeping the VM running** (`devops`) for Lab 5 (Ansible). +- The VM is accessible via `ssh devops@localhost -p 2222`. +- All necessary files (Ansible inventory generated by both Terraform and Pulumi) are already in place. + +### Cleanup Status +- I have **not destroyed** the Terraform or Pulumi resources because the VM itself is not managed by these tools. +- The local files created by Terraform and Pulumi remain in the repository for documentation and future reference. + + +## Challenges & Solutions + +### Challenge 1: Pulumi requiring a backend +**Problem:** Running `pulumi new python` initially prompted for a Pulumi Cloud token. +**Solution:** Used `pulumi login --local` to configure a local state backend, then created the project normally. This kept everything self-contained. + +### Challenge 2: Simulating infrastructure without a real cloud provider +**Problem:** Both tools are designed to provision cloud resources, but I only have a local VM. +**Solution:** I used file resources as a proxy to demonstrate IaC concepts. The files contain metadata about the VM, effectively representing the infrastructure in code. + +### Challenge 3: Downloading Terraform due to geographical restrictions +**Problem:** Direct download of Terraform from the official HashiCorp website was blocked from inside the virtual machine due to regional network restrictions. +**Solution:** I downloaded the Terraform binary on my host machine (Arch Linux) using a working connection, then transferred it to the VM via `scp` over the forwarded SSH port (`scp -P 2222 terraform-provider-local_v2.5.1_x5 devops@localhost:/home/devops/devops_lab/terraform/`). After transferring, I unzipped the archive and moved the binary to `/usr/local/bin/` inside the VM. + +## Screenshots + +1. **Terraform apply output** + ![Terraform Apply](screenshots/terraform-apply.png) + +2. **Pulumi up output** + ![Pulumi Up](screenshots/pulumi-up.png) diff --git a/docs/screenshots/pulumi-up.png b/docs/screenshots/pulumi-up.png new file mode 100644 index 0000000000..264cc47706 Binary files /dev/null and b/docs/screenshots/pulumi-up.png differ diff --git a/docs/screenshots/terraform-apply.png b/docs/screenshots/terraform-apply.png new file mode 100644 index 0000000000..bd8ab162ae Binary files /dev/null and b/docs/screenshots/terraform-apply.png differ 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/.vscode/settings.json b/edge-api/.vscode/settings.json new file mode 100644 index 0000000000..0126e59b82 --- /dev/null +++ b/edge-api/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "wrangler.json": "jsonc" + } +} \ No newline at end of file diff --git a/edge-api/AGENTS.md b/edge-api/AGENTS.md new file mode 100644 index 0000000000..340506a599 --- /dev/null +++ b/edge-api/AGENTS.md @@ -0,0 +1,41 @@ +# Cloudflare Workers + +STOP. Your knowledge of Cloudflare Workers APIs and limits may be outdated. Always retrieve current documentation before any Workers, KV, R2, D1, Durable Objects, Queues, Vectorize, AI, or Agents SDK task. + +## Docs + +- https://developers.cloudflare.com/workers/ +- MCP: `https://docs.mcp.cloudflare.com/mcp` + +For all limits and quotas, retrieve from the product's `/platform/limits/` page. eg. `/workers/platform/limits` + +## Commands + +| Command | Purpose | +|---------|---------| +| `npx wrangler dev` | Local development | +| `npx wrangler deploy` | Deploy to Cloudflare | +| `npx wrangler types` | Generate TypeScript types | + +Run `wrangler types` after changing bindings in wrangler.jsonc. + +## Node.js Compatibility + +https://developers.cloudflare.com/workers/runtime-apis/nodejs/ + +## Errors + +- **Error 1102** (CPU/Memory exceeded): Retrieve limits from `/workers/platform/limits/` +- **All errors**: https://developers.cloudflare.com/workers/observability/errors/ + +## Product Docs + +Retrieve API references and limits from: +`/kv/` · `/r2/` · `/d1/` · `/durable-objects/` · `/queues/` · `/vectorize/` · `/workers-ai/` · `/agents/` + +## Best Practices (conditional) + +If the application uses Durable Objects or Workflows, refer to the relevant best practices: + +- Durable Objects: https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/ +- Workflows: https://developers.cloudflare.com/workflows/build/rules-of-workflows/ diff --git a/edge-api/package-lock.json b/edge-api/package-lock.json new file mode 100644 index 0000000000..8ef7cfbf1e --- /dev/null +++ b/edge-api/package-lock.json @@ -0,0 +1,2906 @@ +{ + "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.0", + "typescript": "^5.5.2", + "vitest": "~3.2.0", + "wrangler": "^4.87.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.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.2.tgz", + "integrity": "sha512-dnlp69efPPg6Uaw2dVqzWRfAWRnYVb1XJ8CyyhIbZeaq4CA5/mLeZ1IEt9QqQxmbdvagjLIm2ZL8BxXv5lH4Yw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.2.tgz", + "integrity": "sha512-OqZTwDRDchGRHHm/hwLOL7uVPB9aUvI0am/eQuWMNyFHf5PSEQmyEeYYheA0EPPKUO/l0uigCp+iaTjoLjVoHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.2.tgz", + "integrity": "sha512-UwRE7CGpvSVEQS8gUMBe1uADWjNnVgP3Iusyda1nSRwNDCsRjnGc7w6El6WLQsXmZTbLZx9cecegumcitNfpmA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.2.tgz", + "integrity": "sha512-gjEtURKLCC5VXm1I+2i1u9OhxFsKAQJKTVB8WvDAHF+oZlq0GTVFOlTlO1q3AlCTE/DF32c16ESvfgqR7343/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.2.tgz", + "integrity": "sha512-Bcl6CYDeAgE70cqZaMojOi/eK63h5Me97ZqAQoh77VPjMysA/4ORQBRGo3rRy45x4MzVlU9uZxs8Uwy7ZaKnBw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.2.tgz", + "integrity": "sha512-LU+TPda3mAE2QB0/Hp5VyeKJivpC6+tlOXd1VMoXV/YFMvk/MNk5iXeBfB4MQGRWyOYVJ01625vjkr0Az98OJQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.2.tgz", + "integrity": "sha512-2QxQrM+KQ7DAW4o22j+XZ6RKdxjLD7BOWTP0Bv0tmjdyhXSsr2Ul1oJDQqh9Zf5qOwTuTc7Ek83mOFaKnodPjg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.2.tgz", + "integrity": "sha512-TbziEu2DVsTEOPif2mKWkMeDMLoYjx95oESa9fkQQK7r/Orta0gnkcDpzwufEcAO2BLBsD7mZkXGFqEdMRRwfw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.2.tgz", + "integrity": "sha512-bO/rVDiDUuM2YfuCUwZ1t1cP+/yqjqz+Xf2VtkdppefuOFS2OSeAfgafaHNkFn0t02hEyXngZkxtGqXcXwO8Rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.2.tgz", + "integrity": "sha512-hr26p7e93Rl0Za+JwW7EAnwAvKkehh12BU1Llm9Ykiibg4uIr2rbpxG9WCf56GuvidlTG9KiiQT/TXT1yAWxTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.2.tgz", + "integrity": "sha512-pOjB/uSIyDt+ow3k/RcLvUAOGpysT2phDn7TTUB3n75SlIgZzM6NKAqlErPhoFU+npgY3/n+2HYIQVbF70P9/A==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.2.tgz", + "integrity": "sha512-2/w+q8jszv9Ww1c+6uJT3OwqhdmGP2/4T17cu8WuwyUuuaCDDJ2ojdyYwZzCxx0GcsZBhzi3HmH+J5pZNXnd+Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.2.tgz", + "integrity": "sha512-11+aL5vKheYgczxtPVVRhdptAM2H7fcDR5Gw4/bTcteuZBlH4oP9f5s9zYO9aGZvoGeBpqXI/9TZZihZ609wKw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.2.tgz", + "integrity": "sha512-i16fokAGK46IVZuV8LIIwMdtqhin9hfYkCh8pf8iC3QU3LpwL+1FSFGej+O7l3E/AoknL6Dclh2oTdnRMpTzFQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.2.tgz", + "integrity": "sha512-49FkKS6RGQoriDSK/6E2GkAsAuU5kETFCh7pG4yD/ylj9rKhTmO3elsnmBvRD4PgJPds5W2PkhC82aVwmUcJ7A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.2.tgz", + "integrity": "sha512-mjYNkHPfGpUR00DuM1ZZIgs64Hpf4bWcz9Z41+4Q+pgDx73UwWdAYyf6EG/lRFldmdHHzgrYyge5akFUW0D3mQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.2.tgz", + "integrity": "sha512-ALyvJz965BQk8E9Al/JDKKDLH2kfKFLTGMlgkAbbYtZuJt9LU8DW3ZoDMCtQpXAltZxwBHevXz5u+gf0yA0YoA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.2.tgz", + "integrity": "sha512-UQjrkIdWrKI626Du8lCQ6MJp/6V1LAo2bOK9OTu4mSn8GGXIkPXk/Vsp4bLHCd9Z9Iz2OTEaokUE90VweJgIYQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.2.tgz", + "integrity": "sha512-bTsRGj6VlSdn/XD4CGyzMnzaBs9bsRxy79eTqTCBsA8TMIEky7qg48aPkvJvFe1HyzQ5oMZdg7AnVlWQSKLTnw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.2.tgz", + "integrity": "sha512-6d4Z3534xitaA1FcMWP7mQPq5zGwBmGbhphh2DwaA1aNIXUu3KTOfwrWpbwI4/Gr0uANo7NTtaykFyO2hPuFLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.2.tgz", + "integrity": "sha512-NetAg5iO2uN7eB8zE5qrZ3CSil+7IJt4WDFLcC75Ymywq1VZVD6qJ6EvNLjZ3rEm6gB7XW5JdT60c6MN35Z85Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.2.tgz", + "integrity": "sha512-NCYhOotpgWZ5kdxCZsv6Iudx0wX8980Q/oW4pNFNihpBKsDbEA1zpkfxJGC0yugsUuyDZ7gL37dbzwhR0VI7pQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.2.tgz", + "integrity": "sha512-RXsaOqXxfoUBQoOgvmmijVxJnW2IGB0eoMO7F8FAjaj0UTywUO/luSqimWBJn04WNgUkeNhh7fs7pESXajWmkg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.2.tgz", + "integrity": "sha512-qdAzEULD+/hzObedtmV6iBpdL5TIbKVztGiK7O3/KYSf+HIzU257+MX1EXJcyIiDbMAqmbwaufcYPvyRryeZtA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.60.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.2.tgz", + "integrity": "sha512-Nd/SgG27WoA9e+/TdK74KnHz852TLa94ovOYySo/yMPuTmpckK/jIF2jSwS3g7ELSKXK13/cVdmg1Z/DaCWKxA==", + "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.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/@types/node": { + "version": "25.6.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz", + "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", + "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.13", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.13.tgz", + "integrity": "sha512-qif0+jGGZoLWdHey3UFHHWP0H7Gbmsk8T5VEqyYFbWqPr1XqvLGBbk/sl8V5exGmcYJklJOhOQq1pV9IcsiFag==", + "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.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.2.tgz", + "integrity": "sha512-J9qZyW++QK/09NyN/zeO0dG/1GdGfyp9lV8ajHnRVLfo/uFsbji5mHnDgn/qYdUHyCkM2N+8VyspgZclfAh0eQ==", + "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.2", + "@rollup/rollup-android-arm64": "4.60.2", + "@rollup/rollup-darwin-arm64": "4.60.2", + "@rollup/rollup-darwin-x64": "4.60.2", + "@rollup/rollup-freebsd-arm64": "4.60.2", + "@rollup/rollup-freebsd-x64": "4.60.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.60.2", + "@rollup/rollup-linux-arm-musleabihf": "4.60.2", + "@rollup/rollup-linux-arm64-gnu": "4.60.2", + "@rollup/rollup-linux-arm64-musl": "4.60.2", + "@rollup/rollup-linux-loong64-gnu": "4.60.2", + "@rollup/rollup-linux-loong64-musl": "4.60.2", + "@rollup/rollup-linux-ppc64-gnu": "4.60.2", + "@rollup/rollup-linux-ppc64-musl": "4.60.2", + "@rollup/rollup-linux-riscv64-gnu": "4.60.2", + "@rollup/rollup-linux-riscv64-musl": "4.60.2", + "@rollup/rollup-linux-s390x-gnu": "4.60.2", + "@rollup/rollup-linux-x64-gnu": "4.60.2", + "@rollup/rollup-linux-x64-musl": "4.60.2", + "@rollup/rollup-openbsd-x64": "4.60.2", + "@rollup/rollup-openharmony-arm64": "4.60.2", + "@rollup/rollup-win32-arm64-msvc": "4.60.2", + "@rollup/rollup-win32-ia32-msvc": "4.60.2", + "@rollup/rollup-win32-x64-gnu": "4.60.2", + "@rollup/rollup-win32-x64-msvc": "4.60.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "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.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz", + "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", + "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.87.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.87.0.tgz", + "integrity": "sha512-lfhfKwLfQlowwgV0xhlYgE9fU3n0I30d4ccGY/rTCEm/n42Mjvlr0Ng3ZPNqlsrsKBcDR531V7dsPkgELvrk/Q==", + "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.20260430.0", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20260430.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.20260430.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260430.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260430.1.tgz", + "integrity": "sha512-ADohZUHf7NBvPp2PdZig2Opxx+hDkk3ve7jrTne3JRx9kDSB73zc4LzcEeEN8LKkbAcqZmvfRJfpChSlusu0lA==", + "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.20260430.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260430.1.tgz", + "integrity": "sha512-/DoYC/1wHs+YRZzzqSQg1/EHB4hiv1yV5U8FnmapRRIzVaPtnt+ApeOXeMrIdKidgKOI8TqQzgBU8xbIM7Cl4Q==", + "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.20260430.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260430.1.tgz", + "integrity": "sha512-koJhBWvEVZPKCVFtMLp2iMHlYr+lFCF47wGbnlKdHVlemV0zTxJEyHI8aLlrhPLhBmOmYLp46rXw09/qJkRIhQ==", + "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.20260430.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260430.1.tgz", + "integrity": "sha512-hMdapNAzNQZDXGGkg4Slydc3fRJP5FUZLJVVcZCW/+imhhJro9Z1rv5n/wfR+txKoSWhTYR8eOp8Pyi2bzLzlw==", + "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.20260430.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260430.1.tgz", + "integrity": "sha512-jS3ffixjb5USOwz4frw4WzCz0HrjVxkgyU3WiYb06N7hBAfN6eOrveAJ4QRef0+suK4V1vQFoB1oKdRBsXe9Dw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/miniflare": { + "version": "4.20260430.0", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260430.0.tgz", + "integrity": "sha512-MWvMm3Siho9Yj7lbJZidLs8hbrRvIcOrif2mnsHQZdvoKfedpea+GaN8XJxbpRcq0B2WzNI1BB1ihdnqes3/ZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "^0.34.5", + "undici": "7.24.8", + "workerd": "1.20260430.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.20260430.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260430.1.tgz", + "integrity": "sha512-KEgIWyiw3Jmn+DCd/L3ePo5fmiiYb/UcwKvDWPf/nLLOiwShDFzDSsegU5NY/JcwgvO/QsLHVi2FYrbkcXNY5Q==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260430.1", + "@cloudflare/workerd-darwin-arm64": "1.20260430.1", + "@cloudflare/workerd-linux-64": "1.20260430.1", + "@cloudflare/workerd-linux-arm64": "1.20260430.1", + "@cloudflare/workerd-windows-64": "1.20260430.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..2f2cac345f --- /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.0", + "typescript": "^5.5.2", + "vitest": "~3.2.0", + "wrangler": "^4.87.0" + } +} \ No newline at end of file diff --git a/edge-api/screenshots/cloudflare-worker-deployments.png b/edge-api/screenshots/cloudflare-worker-deployments.png new file mode 100644 index 0000000000..ff1ef40733 Binary files /dev/null and b/edge-api/screenshots/cloudflare-worker-deployments.png differ diff --git a/edge-api/screenshots/cloudflare-worker-metrics.png b/edge-api/screenshots/cloudflare-worker-metrics.png new file mode 100644 index 0000000000..ffe167bbb0 Binary files /dev/null and b/edge-api/screenshots/cloudflare-worker-metrics.png differ diff --git a/edge-api/screenshots/cloudflare-worker-overview.png b/edge-api/screenshots/cloudflare-worker-overview.png new file mode 100644 index 0000000000..a4c622b9c9 Binary files /dev/null and b/edge-api/screenshots/cloudflare-worker-overview.png differ diff --git a/edge-api/src/index.ts b/edge-api/src/index.ts new file mode 100644 index 0000000000..aafb87299d --- /dev/null +++ b/edge-api/src/index.ts @@ -0,0 +1,126 @@ +export interface Env { + APP_NAME: string; + COURSE_NAME: string; + ENVIRONMENT: string; + API_TOKEN: string; + ADMIN_EMAIL: string; + SETTINGS: KVNamespace; +} + +type JsonValue = Record; + +function json(body: JsonValue, init: ResponseInit = {}): Response { + return Response.json(body, { + headers: { + "cache-control": "no-store", + ...init.headers, + }, + ...init, + }); +} + +function getSecretSummary(env: Env): JsonValue { + return { + apiTokenConfigured: Boolean(env.API_TOKEN), + adminEmailConfigured: Boolean(env.ADMIN_EMAIL), + adminEmailDomain: env.ADMIN_EMAIL?.includes("@") ? env.ADMIN_EMAIL.split("@").at(1) : "not-set", + }; +} + +export default { + async fetch(request, env): Promise { + const url = new URL(request.url); + const startedAt = Date.now(); + + console.log( + JSON.stringify({ + message: "request", + path: url.pathname, + method: request.method, + colo: request.cf?.colo ?? "local", + country: request.cf?.country ?? "local", + }), + ); + + if (url.pathname === "/health") { + return json({ + status: "ok", + app: env.APP_NAME, + timestamp: new Date().toISOString(), + }); + } + + if (url.pathname === "/edge") { + return json({ + app: env.APP_NAME, + deployment: { + platform: "cloudflare-workers", + environment: env.ENVIRONMENT, + workersDev: true, + }, + edge: { + colo: request.cf?.colo ?? "local-dev", + country: request.cf?.country ?? "local-dev", + city: request.cf?.city ?? "local-dev", + asn: request.cf?.asn ?? "local-dev", + httpProtocol: request.cf?.httpProtocol ?? "local-dev", + tlsVersion: request.cf?.tlsVersion ?? "local-dev", + }, + request: { + method: request.method, + path: url.pathname, + userAgent: request.headers.get("user-agent") ?? "unknown", + }, + }); + } + + if (url.pathname === "/config") { + return json({ + app: env.APP_NAME, + course: env.COURSE_NAME, + environment: env.ENVIRONMENT, + secrets: getSecretSummary(env), + note: "Plaintext vars are safe for non-sensitive values only. Secrets are injected by Wrangler and are not committed.", + }); + } + + if (url.pathname === "/counter") { + const rawVisits = await env.SETTINGS.get("visits"); + const visits = Number(rawVisits ?? "0") + 1; + await env.SETTINGS.put("visits", String(visits)); + + return json({ + key: "visits", + visits, + persistedIn: "Workers KV", + }); + } + + if (url.pathname === "/") { + return json({ + app: env.APP_NAME, + course: env.COURSE_NAME, + message: "Hello from Cloudflare Workers edge API", + environment: env.ENVIRONMENT, + timestamp: new Date().toISOString(), + durationMs: Date.now() - startedAt, + routes: [ + { path: "/", method: "GET", description: "Service metadata" }, + { path: "/health", method: "GET", description: "Health check" }, + { path: "/edge", method: "GET", description: "Cloudflare edge request metadata" }, + { path: "/config", method: "GET", description: "Vars and secret presence" }, + { path: "/counter", method: "GET", description: "KV-backed persisted counter" }, + ], + }); + } + + return json( + { + error: "not_found", + message: "Route does not exist", + path: url.pathname, + }, + { status: 404 }, + ); + }, +} satisfies ExportedHandler; 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..31885554a2 --- /dev/null +++ b/edge-api/test/index.spec.ts @@ -0,0 +1,36 @@ +import { + env, + createExecutionContext, + waitOnExecutionContext, + SELF, +} from "cloudflare:test"; +import { describe, it, expect } from "vitest"; +import worker from "../src/index"; + +const IncomingRequest = Request; + +describe("edge API worker", () => { + it("responds to /health with JSON status", async () => { + const request = new IncomingRequest("http://example.com/health"); + const ctx = createExecutionContext(); + const response = await worker.fetch(request, env, ctx); + await waitOnExecutionContext(ctx); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("application/json"); + await expect(response.json()).resolves.toMatchObject({ + status: "ok", + app: "edge-api", + }); + }); + + it("returns 404 JSON for unknown routes", async () => { + const response = await SELF.fetch("https://example.com/unknown"); + + expect(response.status).toBe(404); + await expect(response.json()).resolves.toMatchObject({ + error: "not_found", + path: "/unknown", + }); + }); +}); 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..6f760c1b75 --- /dev/null +++ b/edge-api/worker-configuration.d.ts @@ -0,0 +1,13571 @@ +/* eslint-disable */ +// Generated by Wrangler by running `wrangler types` (hash: 965717cb844d31c26d7a06dbf4c2c789) +// Runtime types generated with workerd@1.20260430.1 2026-05-01 nodejs_compat +declare namespace Cloudflare { + interface GlobalProps { + mainModule: typeof import("./src/index"); + } + interface Env { + SETTINGS: KVNamespace; + APP_NAME: "edge-api"; + COURSE_NAME: "devops-core"; + ENVIRONMENT: "production"; + API_TOKEN: string; + ADMIN_EMAIL: string; + } +} +interface Env extends Cloudflare.Env {} +type StringifyValues> = { + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; +}; +declare namespace NodeJS { + interface ProcessEnv extends StringifyValues> {} +} + +// 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(type?: ((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 interface RollbackContext { + error: Error; + output: NonNullable | undefined; + stepName: string; + } + export interface StepPromise extends Promise { + rollback(fn: (ctx: RollbackContext) => Promise): StepPromise; + rollback(config: WorkflowStepConfig, fn: (ctx: RollbackContext) => Promise): StepPromise; + } + export abstract class WorkflowStep { + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): StepPromise; + do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): StepPromise; + sleep: (name: string, duration: WorkflowSleepDuration) => Promise; + sleepUntil: (name: string, timestamp: Date | number) => Promise; + waitForEvent>(name: string, options: { + type: string; + timeout?: WorkflowTimeoutDuration | number; + }): StepPromise>; + } + 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..dc5f61de02 --- /dev/null +++ b/edge-api/wrangler.jsonc @@ -0,0 +1,64 @@ +/** + * 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-01", + "workers_dev": true, + "preview_urls": true, + "observability": { + "enabled": true + }, + "upload_source_maps": true, + "compatibility_flags": [ + "nodejs_compat" + ], + "vars": { + "APP_NAME": "edge-api", + "COURSE_NAME": "devops-core", + "ENVIRONMENT": "production" + }, + "kv_namespaces": [ + { + "binding": "SETTINGS", + "id": "d1434a1bf2e5471598ecbcd86fa64596" + } + ], + "secrets": { + "required": [ + "API_TOKEN", + "ADMIN_EMAIL" + ] + } + /** + * Smart Placement + * https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement + */ + // "placement": { "mode": "smart" } + /** + * Bindings + * Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform, including + * databases, object storage, AI inference, real-time communication and more. + * https://developers.cloudflare.com/workers/runtime-apis/bindings/ + */ + /** + * Environment Variables + * https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables + * Note: Use secrets to store sensitive data. + * https://developers.cloudflare.com/workers/configuration/secrets/ + */ + // "vars": { "MY_VARIABLE": "production_value" } + /** + * Static Assets + * https://developers.cloudflare.com/workers/static-assets/binding/ + */ + // "assets": { "directory": "./public/", "binding": "ASSETS" } + /** + * Service Bindings (communicate between multiple Workers) + * https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings + */ + // "services": [ { "binding": "MY_SERVICE", "service": "my-service" } ] +} diff --git a/k8s/ARGOCD.md b/k8s/ARGOCD.md new file mode 100644 index 0000000000..5365a85eaf --- /dev/null +++ b/k8s/ARGOCD.md @@ -0,0 +1,365 @@ +# Lab 13: GitOps with ArgoCD + +## ArgoCD Setup + +### Installation + +ArgoCD was installed into a dedicated `argocd` namespace with the official Helm chart. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ helm list -n argocd +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +argocd argocd 1 2026-04-17 13:55:04.180596419 +0300 MSK deployed argo-cd-9.5.2 v3.3.7 +``` + +All ArgoCD components were running after installation. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get pods -n argocd -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +argocd-application-controller-0 1/1 Running 0 3m14s 10.244.0.149 minikube +argocd-applicationset-controller-59f6b7dd64-w4cvz 1/1 Running 0 3m14s 10.244.0.148 minikube +argocd-dex-server-7b9588c494-cckh4 1/1 Running 0 3m14s 10.244.0.151 minikube +argocd-notifications-controller-8f6855454-kxdrr 1/1 Running 0 3m14s 10.244.0.152 minikube +argocd-redis-dc6b586fc-brr5r 1/1 Running 0 3m14s 10.244.0.150 minikube +argocd-repo-server-5f4d44d9f8-rz7d2 1/1 Running 0 3m14s 10.244.0.153 minikube +argocd-server-5f777b877f-2bl4c 1/1 Running 0 3m14s 10.244.0.147 minikube +``` + +### UI and CLI Access + +The UI was exposed locally through port forwarding: + +```bash +kubectl port-forward svc/argocd-server -n argocd 8080:443 +``` + +The initial admin password was read from the generated secret: + +```bash +kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 -d +``` + +ArgoCD CLI was installed locally on the host and logged in through the port-forwarded endpoint. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ argocd version --client +argocd: v3.3.3+unknown + BuildDate: 2026-03-10T01:28:07Z + GitTag: 3.3.3 + GoVersion: go1.26.1-X:nodwarf5 + Platform: linux/amd64 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ argocd login localhost:8080 --username admin --password --insecure +'admin:login' logged in successfully +Context 'localhost:8080' updated +``` + + +## Application Configuration + +### Manifests + +ArgoCD manifests were added under `k8s/argocd/`: + +```text +k8s/argocd/ +├── application.yaml +├── application-dev.yaml +├── application-prod.yaml +└── applicationset.yaml +``` + +The required Application manifests use the existing Helm chart: +- target revision in the current manifests: `lab13` +- chart path: `k8s/devops-python` +- cluster destination: `https://kubernetes.default.svc` +- single app values: `values.yaml` +- dev values: `values-dev.yaml` +- prod values: `values-prod.yaml` + + +### Application Creation + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl apply -f k8s/argocd/application.yaml -f k8s/argocd/application-dev.yaml -f k8s/argocd/application-prod.yaml +application.argoproj.io/python-app created +application.argoproj.io/python-app-dev created +application.argoproj.io/python-app-prod created +``` + +Initial status showed that dev synced automatically, while the default and prod apps waited for manual sync. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ argocd app list +NAME CLUSTER NAMESPACE PROJECT STATUS HEALTH SYNCPOLICY CONDITIONS REPO PATH TARGET +argocd/python-app https://kubernetes.default.svc default default OutOfSync Missing Manual https://github.com/s3rap1s/DevOps-Core-Course.git k8s/devops-python lab13 +argocd/python-app-dev https://kubernetes.default.svc dev default Synced Healthy Auto-Prune https://github.com/s3rap1s/DevOps-Core-Course.git k8s/devops-python lab13 +argocd/python-app-prod https://kubernetes.default.svc prod default OutOfSync Missing Manual https://github.com/s3rap1s/DevOps-Core-Course.git k8s/devops-python lab13 +``` + +Manual sync was then triggered for the default and prod applications. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ argocd app sync python-app +Operation: Sync +Sync Revision: 10a3886298116dce2658fe2ed76a79127c6ed8a0 +Phase: Succeeded +Start: 2026-04-17 14:02:43 +0300 MSK +Finished: 2026-04-17 14:03:21 +0300 MSK +Duration: 38s +Message: successfully synced (no more tasks) +``` + +This covers the GitOps workflow mechanically: the desired state is stored in Git, ArgoCD detects when the cluster is `OutOfSync`, and a manual sync applies the Git state to the cluster. For a real branch update workflow, the next change should be committed and pushed to `lab14`, then ArgoCD will detect the new revision and sync it from Git. + + +## Multi-Environment Deployment + +### Configuration Differences + +Development uses `values-dev.yaml`: + +- namespace: `dev` +- replicas: `1` +- service type: `NodePort` +- smaller CPU and memory requests/limits +- auto-sync enabled with `prune` and `selfHeal` + +Production uses `values-prod.yaml`: + +- namespace: `prod` +- replicas: `5` +- service type: `LoadBalancer` +- higher CPU and memory requests/limits +- manual sync only + +Production remains manual because release timing should be controlled explicitly. This avoids an automatic production rollout immediately after every Git change. + +### Environment Verification + +Dev resources: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get deploy,svc,pvc -n dev -l app.kubernetes.io/instance=python-app-dev +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/python-app-dev-devops-python 1/1 1 1 3m25s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/python-app-dev-devops-python NodePort 10.107.239.20 80:31668/TCP 3m25s + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE +persistentvolumeclaim/python-app-dev-devops-python-data Bound pvc-199f741f-23cf-49c1-97ac-aad89de6c21f 100Mi RWO standard 3m25s +``` + +Prod resources: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get deploy,svc,pvc -n prod -l app.kubernetes.io/instance=python-app-prod +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/python-app-prod-devops-python 5/5 5 5 65s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/python-app-prod-devops-python LoadBalancer 10.98.21.110 80:30452/TCP 65s + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE +persistentvolumeclaim/python-app-prod-devops-python-data Bound pvc-993a550c-3c58-470b-9cb2-77e92e1158de 100Mi RWO standard 65s +``` + +The prod Service has `EXTERNAL-IP: ` because Minikube does not allocate LoadBalancer IPs without `minikube tunnel`. The deployment itself was healthy and the service was still reachable through the assigned NodePort. + +Application health checks through Minikube: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ curl -s http://192.168.49.2:31668/health +{"status":"healthy","timestamp":"2026-04-17T11:07:34.266765+00:00","uptime_seconds":131} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ curl -s http://192.168.49.2:30452/health +{"status":"healthy","timestamp":"2026-04-17T11:07:34.278974+00:00","uptime_seconds":229} +``` + + +## Self-Healing and Drift Tests + +### Manual Scale Drift + +The dev deployment is defined as `replicaCount: 1` in `values-dev.yaml`. It was manually scaled to 5 replicas. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get deployment python-app-dev-devops-python -n dev -o jsonpath='{.spec.replicas}{" desired, "}{.status.readyReplicas}{" ready\n"}'; kubectl scale deployment python-app-dev-devops-python -n dev --replicas=5 +2026-04-17 14:04:58 MSK +1 desired, 1 ready +deployment.apps/python-app-dev-devops-python scaled +``` + +Immediately after the manual change: + +```bash +2026-04-17 14:04:58 MSK +5 desired, 1 ready +``` + +ArgoCD self-healing reverted the deployment back to the Git-defined value. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get deployment python-app-dev-devops-python -n dev -o jsonpath='{.spec.replicas}{" desired, "}{.status.readyReplicas}{" ready\n"}' +2026-04-17 14:05:08 MSK +1 desired, 1 ready +``` + +### Pod Deletion + +A dev pod was manually deleted. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get pods -n dev -l app.kubernetes.io/instance=python-app-dev; kubectl delete pod -n dev -l app.kubernetes.io/instance=python-app-dev +2026-04-17 14:05:16 MSK +NAME READY STATUS RESTARTS AGE +python-app-dev-devops-python-558d6b487b-8gjp4 1/1 Running 0 3m55s +pod "python-app-dev-devops-python-558d6b487b-8gjp4" deleted from dev namespace +``` + +Kubernetes recreated the pod through the Deployment/ReplicaSet controller. + +```bash +2026-04-17 14:05:47 MSK +NAME READY STATUS RESTARTS AGE +python-app-dev-devops-python-558d6b487b-88bkg 1/1 Running 0 31s +``` + +This was Kubernetes self-healing, not ArgoCD self-healing. Kubernetes restored the missing pod because the ReplicaSet still desired one replica. + +### Configuration Drift + +The dev environment ConfigMap was manually changed from the Git-defined value `LOG_LEVEL=info` to `LOG_LEVEL=debug`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl patch configmap python-app-dev-devops-python-env -n dev --type merge -p '{"data":{"LOG_LEVEL":"debug"}}'; kubectl get configmap python-app-dev-devops-python-env -n dev -o jsonpath='{.data.LOG_LEVEL}{"\n"}' +2026-04-17 14:06:48 MSK +configmap/python-app-dev-devops-python-env patched +debug +``` + +ArgoCD detected and reverted the managed ConfigMap field. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get configmap python-app-dev-devops-python-env -n dev -o jsonpath='{.data.LOG_LEVEL}{"\n"}' +2026-04-17 14:07:13 MSK +info +``` + +### Behavior Analysis + +ArgoCD syncs Kubernetes resources back to the desired state stored in Git. In this lab, the dev app used automated sync with `prune` and `selfHeal`, so manual changes to managed fields were reverted automatically. + +Kubernetes self-healing is different: Deployment and ReplicaSet controllers recreate missing pods even when ArgoCD does nothing. Deleting a pod does not change Git-defined configuration; it only removes an instance managed by Kubernetes. + +By default, ArgoCD polls Git every 3 minutes. Drift inside the cluster can also trigger self-healing for automated applications when `selfHeal` is enabled. + + +## UI Screenshots + +Applications list with `python-app`, `python-app-dev`, and `python-app-prod`: + +![ArgoCD applications list](argocd/screenshots/argocd-applications-list.png) + +Dev application details: + +![ArgoCD dev details](argocd/screenshots/argocd-dev-details.png) + +Prod application details: + +![ArgoCD prod details](argocd/screenshots/argocd-prod-details.png) + + +## ApplicationSet Bonus + +The bonus ApplicationSet manifest is stored in `k8s/argocd/applicationset.yaml`. + +It uses a List generator to define the environment-specific parameters: + +- `env` +- `namespace` +- `valuesFile` +- `autoSync` + +The template then generates one Application per environment with the matching Helm values file. + +```yaml +generators: + - list: + elements: + - env: dev + namespace: dev + valuesFile: values-dev.yaml + autoSync: "true" + - env: prod + namespace: prod + valuesFile: values-prod.yaml + autoSync: "false" +``` + +The ApplicationSet uses `templatePatch` to keep the same sync policy behavior as the individual Application manifests: + +- dev gets automated sync with `prune` and `selfHeal` +- prod stays manual + +This is needed because both generated Applications share one base template, but their sync policies are different. + +### Replacing Individual Applications + +The individual dev/prod Applications were removed after checking that they had no finalizers, so deleting the Application CRs did not delete the already deployed workloads. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get application python-app-dev python-app-prod -n argocd -o jsonpath='{range .items[*]}{.metadata.name}{": finalizers="}{.metadata.finalizers}{"\n"}{end}' +python-app-dev: finalizers= +python-app-prod: finalizers= +``` + +Then the ApplicationSet was applied. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl delete application python-app-dev python-app-prod -n argocd +application.argoproj.io "python-app-dev" deleted from argocd namespace +application.argoproj.io "python-app-prod" deleted from argocd namespace +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl apply -f k8s/argocd/applicationset.yaml +applicationset.argoproj.io/python-app-set created +``` + +Generated Applications: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get applicationsets -n argocd +NAME AGE +python-app-set 7s +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get applications -n argocd +NAME SYNC STATUS HEALTH STATUS +python-app Synced Healthy +python-app-dev Synced Healthy +python-app-prod Synced Progressing +``` + +Both generated Applications are owned by the ApplicationSet. Dev has automated sync enabled, while prod has no automated sync policy. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab13 λ kubectl get applications python-app-dev python-app-prod -n argocd -o jsonpath='{range .items[*]}{.metadata.name}{" owner="}{.metadata.ownerReferences[0].kind}{"/"}{.metadata.ownerReferences[0].name}{" sync="}{.status.sync.status}{" health="}{.status.health.status}{" policy="}{.spec.syncPolicy.automated}{"\n"}{end}' +python-app-dev owner=ApplicationSet/python-app-set sync=Synced health=Healthy policy={"prune":true,"selfHeal":true} +python-app-prod owner=ApplicationSet/python-app-set sync=Synced health=Progressing policy= +``` + +The generated Application names are: + +- `python-app-dev` +- `python-app-prod` + +ApplicationSet is useful when the same application must be deployed repeatedly across environments, clusters, tenants, or directories. For a small number of environments, individual Application manifests are simpler. For many repeated deployments, ApplicationSet reduces duplication and keeps environment parameters in one generator. diff --git a/k8s/CONFIGMAPS.md b/k8s/CONFIGMAPS.md new file mode 100644 index 0000000000..e4c42024be --- /dev/null +++ b/k8s/CONFIGMAPS.md @@ -0,0 +1,437 @@ +# Lab 12: ConfigMaps & Persistent Volumes + +## 1. Application Changes + +### Implementation + +The Python application was updated to persist a visits counter in a file and expose it through a new `/visits` endpoint. + +Main changes: + +- `app_python/app.py` + - added `DATA_DIR`, `VISITS_FILE`, and `CONFIG_FILE` + - added `read_visits_count()`, `write_visits_count()`, and `increment_visits_count()` + - added `VISITS_LOCK` to avoid concurrent write races + - writes the counter with an atomic temporary-file replacement + - root endpoint `/` now increments and returns `runtime.visits_count` + - new `/visits` endpoint returns the current value without incrementing it +- `monitoring/docker-compose.yml` + - added persistent volume `app-python-data` + - mounted it to `/app/data` + - passed `DATA_DIR=/app/data` +- `app_python/README.md` + - updated runtime and persistence usage examples + + +### Local Docker Evidence + +The local container was started with a Docker volume mounted to `/app/data`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ docker compose ps app-python +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +app-python s3rap1s/devops-info-service:latest "sh -c 'mkdir -p /ap…" app-python About a minute ago Up About a minute (healthy) 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp +``` + +The root endpoint was called twice. The first response returned `visits_count: 1`, and the second returned `visits_count: 2`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://localhost:5000/ +{"configuration":{"environment":{"APP_ENV":"undefined","CONFIG_FILE":"/app_python/config/config.json","DATA_DIR":"/app/data","FEATURE_GREETINGS":"undefined","LOG_LEVEL":"undefined"},"file":{}},"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Visit counter","method":"GET","path":"/visits"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"172.20.0.1","method":"GET","path":"/","user_agent":"curl/8.18.0"},"runtime":{"current_time":"2026-04-15T10:22:42.476879+00:00","timezone":"UTC","uptime_human":"0 hours, 0 minutes","uptime_seconds":10,"visits_count":1},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"2.0.0"},"system":{"architecture":"x86_64","cpu_count":12,"hostname":"10a3e4f65471","platform":"Linux","platform_version":"6.18.9-arch1-2","python_version":"3.13.13"}} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://localhost:5000/ +{"configuration":{"environment":{"APP_ENV":"undefined","CONFIG_FILE":"/app_python/config/config.json","DATA_DIR":"/app/data","FEATURE_GREETINGS":"undefined","LOG_LEVEL":"undefined"},"file":{}},"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Visit counter","method":"GET","path":"/visits"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"172.20.0.1","method":"GET","path":"/","user_agent":"curl/8.18.0"},"runtime":{"current_time":"2026-04-15T10:22:42.482292+00:00","timezone":"UTC","uptime_human":"0 hours, 0 minutes","uptime_seconds":10,"visits_count":2},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"2.0.0"},"system":{"architecture":"x86_64","cpu_count":12,"hostname":"10a3e4f65471","platform":"Linux","platform_version":"6.18.9-arch1-2","python_version":"3.13.13"}} +``` + +The `/visits` endpoint and the visits file both returned the same persisted value. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://localhost:5000/visits +{"file":"/app/data/visits","visits":2} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ docker compose exec app-python cat /app/data/visits +2 +``` + +After restarting the container, the counter was still present. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ docker compose restart app-python + Container app-python Restarting + Container app-python Started +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ docker compose ps app-python +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +app-python s3rap1s/devops-info-service:latest "sh -c 'mkdir -p /ap…" app-python 6 minutes ago Up 12 seconds (healthy) 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://localhost:5000/visits +{"file":"/app/data/visits","visits":2} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ docker compose exec app-python cat /app/data/visits +2 +``` + + +## 2. ConfigMap Implementation + +### Implementation + +The Helm chart was extended with a `files/` directory and a new `templates/configmap.yaml`. + +`k8s/devops-python/files/config.json` stores the file-based application configuration: + +```json +{ + "application_name": "{{ .Values.configFile.applicationName }}", + "environment": "{{ .Values.configFile.environment }}", + "settings": { + "featureGreeting": {{ .Values.configFile.settings.featureGreeting }}, + "maxVisitsDisplay": {{ .Values.configFile.settings.maxVisitsDisplay }} + } +} +``` + +`k8s/devops-python/templates/configmap.yaml` renders two ConfigMaps: + +- `lab12-release-devops-python-config` + - stores `config.json` + - uses `.Files.Get` together with `tpl` +- `lab12-release-devops-python-env` + - stores environment variables from `.Values.configEnv` + +The deployment uses both ConfigMaps: + +- the file ConfigMap is mounted as `/config` +- the application reads `/config/config.json` +- the environment ConfigMap is injected through `envFrom` + +### Verification Outputs + +`kubectl get configmap,pvc`: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl get configmap,pvc -l app.kubernetes.io/instance=lab12-release +NAME DATA AGE +configmap/lab12-release-devops-python-config 1 48s +configmap/lab12-release-devops-python-env 5 48s + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE +persistentvolumeclaim/lab12-release-devops-python-data Bound pvc-0cf99f5e-1543-4ab8-b8f9-dd40041fca7b 100Mi RWO standard 48s +``` + +File content inside pod: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-648c79689f-74xfn -- cat /config/config.json +Defaulted container "app" out of: app, volume-permissions (init) +{ + "application_name": "devops-info-service", + "environment": "development", + "settings": { + "featureGreeting": true, + "maxVisitsDisplay": 10 + } +} +``` + +Environment variables inside pod: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-648c79689f-74xfn +Defaulted container "app" out of: app, volume-permissions (init) +development +info +true +/data +/config/config.json +``` + +This confirms both ConfigMap delivery methods: + +- file-based configuration through `/config/config.json` +- key-value environment injection through `envFrom` + + +## 3. Persistent Volume + +### Implementation + +Persistent storage is defined in `k8s/devops-python/templates/pvc.yaml`. + +The PVC configuration is: + +- `accessModes: ReadWriteOnce` +- `resources.requests.storage: 100Mi` +- `storageClassName` configurable via values +- current Minikube deployment uses the default `standard` storage class + +The deployment mounts the claim at `/data`, and the application stores the counter in `/data/visits`. + +Because the application container runs as UID `999`, an init container prepares the mounted directory: + +- image: `busybox:1.36.1` +- command: `mkdir -p /data && chown -R 999:999 /data` + +### Persistence Test Evidence + +The application was accessed through the NodePort service twice. The first response returned `visits_count: 1`, and the second returned `visits_count: 2`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://192.168.49.2:32172/ +{"configuration":{"environment":{"APP_ENV":"development","CONFIG_FILE":"/config/config.json","DATA_DIR":"/data","FEATURE_GREETINGS":"true","LOG_LEVEL":"info"},"file":{"application_name":"devops-info-service","environment":"development","settings":{"featureGreeting":true,"maxVisitsDisplay":10}}},"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Visit counter","method":"GET","path":"/visits"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"10.244.0.1","method":"GET","path":"/","user_agent":"curl/8.18.0"},"runtime":{"current_time":"2026-04-15T10:26:15.139157+00:00","timezone":"UTC","uptime_human":"0 hours, 0 minutes","uptime_seconds":47,"visits_count":1},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"2.0.0"},"system":{"architecture":"x86_64","cpu_count":12,"hostname":"lab12-release-devops-python-648c79689f-74xfn","platform":"Linux","platform_version":"6.18.9-arch1-2","python_version":"3.13.13"}} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://192.168.49.2:32172/ +{"configuration":{"environment":{"APP_ENV":"development","CONFIG_FILE":"/config/config.json","DATA_DIR":"/data","FEATURE_GREETINGS":"true","LOG_LEVEL":"info"},"file":{"application_name":"devops-info-service","environment":"development","settings":{"featureGreeting":true,"maxVisitsDisplay":10}}},"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Visit counter","method":"GET","path":"/visits"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"10.244.0.1","method":"GET","path":"/","user_agent":"curl/8.18.0"},"runtime":{"current_time":"2026-04-15T10:26:15.144858+00:00","timezone":"UTC","uptime_human":"0 hours, 0 minutes","uptime_seconds":47,"visits_count":2},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"2.0.0"},"system":{"architecture":"x86_64","cpu_count":12,"hostname":"lab12-release-devops-python-648c79689f-74xfn","platform":"Linux","platform_version":"6.18.9-arch1-2","python_version":"3.13.13"}} +``` + +Counter value before pod deletion: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://192.168.49.2:32172/visits +{"file":"/data/visits","visits":2} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-648c79689f-74xfn -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +2 +``` + +Pod deletion command: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl delete pod lab12-release-devops-python-648c79689f-74xfn +pod "lab12-release-devops-python-648c79689f-74xfn" deleted from default namespace +``` + +New pod startup after deletion: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl get pods -l app.kubernetes.io/instance=lab12-release -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +lab12-release-devops-python-648c79689f-74xfn 1/1 Terminating 0 90s 10.244.0.118 minikube +lab12-release-devops-python-648c79689f-bjpxd 1/1 Running 0 18s 10.244.0.120 minikube +``` + +Counter value after the new pod started: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ curl -s http://192.168.49.2:32172/visits +{"file":"/data/visits","visits":2} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-648c79689f-bjpxd -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +2 +``` + +This verifies that the visits counter survived pod deletion because the data was stored on the PVC, not in the container filesystem. + + +## 4. ConfigMap vs Secret + +### When to Use ConfigMap + +ConfigMap should be used for non-sensitive configuration such as: + +- application name +- environment name +- feature flags +- log levels +- file paths + +### When to Use Secret + +Secret should be used for sensitive values such as: + +- passwords +- API tokens +- private keys +- database credentials + +### Key Differences + +- ConfigMap is intended for plain configuration data +- Secret is intended for confidential data +- both can be mounted as files or exposed as environment variables +- Secret values are still only base64-encoded in Kubernetes manifests, so stronger protection usually requires encryption at rest and access control + + +## 5. ConfigMap Hot Reload + +### Default Update Behavior + +The mounted ConfigMap was updated directly without restarting the pod. + +Initial pod state: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl get pods -l app.kubernetes.io/instance=lab12-release -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +lab12-release-devops-python-648c79689f-bjpxd 1/1 Running 0 36m 10.244.0.120 minikube +``` + +The mounted file initially contained the original value: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-648c79689f-bjpxd -- cat /config/config.json +Defaulted container "app" out of: app, volume-permissions (init) +{ + "application_name": "devops-info-service", + "environment": "development", + "settings": { + "featureGreeting": true, + "maxVisitsDisplay": 10 + } +} +``` + +The ConfigMap was then patched directly: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl patch configmap lab12-release-devops-python-config +configmap/lab12-release-devops-python-config patched +``` + +The file inside the running pod updated without recreating the pod. The measured delay was `31s`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-648c79689f-bjpxd +Detected update after 31s +{ + "application_name": "devops-info-service", + "environment": "live-patched", + "settings": { + "featureGreeting": true, + "maxVisitsDisplay": 15 + } +} +``` + +This matches the expected Kubernetes behavior for mounted ConfigMaps: updates are not instant, but they propagate after the kubelet refresh cycle. + +### subPath Limitation + +`subPath` should be avoided for hot-reloaded configuration files. + +Why: + +- a normal ConfigMap directory mount is updated by Kubernetes in place +- a `subPath` file mount is effectively a bind-mounted copy +- when the ConfigMap changes, that copied file is not refreshed inside the container + +Use `subPath` only when a fixed file path is required and live updates are not needed. For auto-updating mounted config, mount the full directory, as done in this lab with `/config`. + +### Chosen Reload Approach + +The implemented reload approach is pod restart via checksum annotation. + +The deployment template now includes: + +```yaml +annotations: + checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} +``` + +This means: + +- when the rendered ConfigMap changes during `helm upgrade` +- the checksum value changes +- the Deployment pod template changes +- Kubernetes creates a new ReplicaSet and rolls out new pods automatically + +### Helm Upgrade Pattern Evidence + +First, the chart renders the checksum annotation: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ helm template lab12-release k8s/devops-python -f k8s/devops-python/values-dev.yaml --set image.tag=lab12 --set secret.username=appuser --set secret.password=appsecret + name: lab12-release-devops-python + name: lab12-release-devops-python-secret + name: lab12-release-devops-python-config + name: lab12-release-devops-python-env + name: lab12-release-devops-python-data + name: lab12-release-devops-python +kind: Deployment + name: lab12-release-devops-python + checksum/config: 0cef5b51a9aff2a47a2c5f65d25a3bcd85a43af1514d28b4ed5e3e3ee1fff3fb + name: lab12-release-devops-python-post-install + name: lab12-release-devops-python-pre-install +``` + +The release was upgraded with changed ConfigMap values: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ helm upgrade lab12-release k8s/devops-python -f k8s/devops-python/values-dev.yaml --set image.tag=lab12 --set secret.username=appuser --set secret.password=appsecret --set configFile.environment=bonus-reload --set configEnv.APP_ENV=bonus-reload --set configFile.settings.maxVisitsDisplay=25 --wait --wait-for-jobs --force-conflicts +Release "lab12-release" has been upgraded. Happy Helming! +NAME: lab12-release +LAST DEPLOYED: Wed Apr 15 14:04:28 2026 +NAMESPACE: default +STATUS: deployed +REVISION: 3 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +After the upgrade, Kubernetes created a new pod: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl get pods -l app.kubernetes.io/instance=lab12-release -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +lab12-release-devops-python-648c79689f-bjpxd 1/1 Terminating 0 38m 10.244.0.120 minikube +lab12-release-devops-python-75d7bf4d94-bl8dw 1/1 Running 0 20s 10.244.0.121 minikube +``` + +The new deployment template contains a different checksum: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl get deployment lab12-release-devops-python -o yaml + name: lab12-release-devops-python + checksum/config: 195b6fddf4edff2b38e3f2d57464a0831ab6d2943a7a64bc5af3460ae5ede3d8 + name: lab12-release-devops-python-env + name: lab12-release-devops-python-secret + image: s3rap1s/devops-info-service:lab12 + image: busybox:1.36.1 + serviceAccountName: lab12-release-devops-python + name: lab12-release-devops-python-config +``` + +The new pod received the updated file-based and environment-based configuration: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-75d7bf4d94-bl8dw -- cat /config/config.json +Defaulted container "app" out of: app, volume-permissions (init) +{ + "application_name": "devops-info-service", + "environment": "bonus-reload", + "settings": { + "featureGreeting": true, + "maxVisitsDisplay": 25 + } +} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab12 λ kubectl exec lab12-release-devops-python-75d7bf4d94-bl8dw +Defaulted container "app" out of: app, volume-permissions (init) +bonus-reload +info +true +/data +/config/config.json +``` + +This demonstrates the chosen reload mechanism: changing the ConfigMap through Helm changes the checksum annotation, which forces a rolling update and applies the new configuration to new pods. diff --git a/k8s/HELM.md b/k8s/HELM.md new file mode 100644 index 0000000000..d1a9b7643a --- /dev/null +++ b/k8s/HELM.md @@ -0,0 +1,572 @@ +# Lab 10: Helm Package Manager + +## Chart Overview + +### Implementation + +Chart structure: + +```text +k8s/devops-python/ +├── Chart.yaml # contains chart metadata +├── values.yaml # contains default configuration +├── values-dev.yaml # contains development overrides +├── values-prod.yaml # contains production overrides +└── templates/ + ├── _helpers.tpl # defines reusable names and labels + ├── deployment.yaml # renders the application Deployment + ├── service.yaml # renders the Service + ├── pre-install-job.yaml # defines the pre-install hook + └── post-install-job.yaml # defines the post-install hook +``` + +The values are organized by concern: + +- `image` for repository, tag, and pull policy +- `service` for service type and ports +- `container` for container port +- `env` for environment variables +- `resources` for requests and limits +- `livenessProbe` and `readinessProbe` for health checks +- `hooks` for hook image and weights + +### Helm Fundamentals Evidence + +#### Helm Version + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm version +version.BuildInfo{Version:"v4.1.3", GitCommit:"c94d381b03be117e7e57908edbf642104e00eb8f", GitTreeState:"", GoVersion:"go1.26.1-X:nodwarf5", KubeClientVersion:"v1.35"} +``` + +#### Public Chart Exploration + +I explored a public chart from the `prometheus-community` repository. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm show chart prometheus-community/prometheus +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/ +icon: https://raw.githubusercontent.com/prometheus/prometheus.github.io/master/assets/prometheus_logo-cb55bb5c346.png +keywords: +- monitoring +- prometheus +kubeVersion: '>=1.19.0-0' +maintainers: +- email: gianrubio@gmail.com + name: gianrubio + url: https://github.com/gianrubio +- email: zanhsieh@gmail.com + name: zanhsieh + url: https://github.com/zanhsieh +- email: miroslav.hadzhiev@gmail.com + name: Xtigyro + url: https://github.com/Xtigyro +- email: naseem@transit.app + name: naseemkullah + url: https://github.com/naseemkullah +- email: rootsandtrees@posteo.de + name: zeritti + url: https://github.com/zeritti +name: prometheus +sources: +- https://github.com/prometheus/alertmanager +- https://github.com/prometheus/prometheus +- https://github.com/prometheus/pushgateway +- https://github.com/prometheus/node_exporter +- https://github.com/kubernetes/kube-state-metrics +type: application +version: 28.14.1 +``` + +Helm's main value proposition is that it turns static Kubernetes YAML into reusable, parameterized, and versioned application packages that can be installed, upgraded, rolled back, and customized for different environments. + + +## Configuration Guide + +### Important Values + +Default chart values: + +```yaml +nameOverride: "" +fullnameOverride: "" + +replicaCount: 3 + +image: + repository: s3rap1s/devops-info-service + tag: "v2" + pullPolicy: IfNotPresent + +service: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: null + +container: + port: 5000 + +env: + - name: PORT + value: "5000" + - name: HOST + value: "0.0.0.0" + +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 200m + memory: 256Mi + +livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 15 + periodSeconds: 10 + +readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 5 + +hooks: + image: busybox:1.36.1 + preInstall: + enabled: true + weight: -5 + postInstall: + enabled: true + weight: 5 +``` + +### Environment Differences + +`values-dev.yaml`: + +- `replicaCount: 1` +- reduced resources +- `service.type: NodePort` +- shorter health-check delays + +`values-prod.yaml`: + +- `replicaCount: 5` +- higher resource requests and limits +- `service.type: LoadBalancer` +- more conservative health-check delays + +### Example Usage + +- Development installation: `helm install lab10-release k8s/devops-python -f k8s/devops-python/values-dev.yaml` +- Production upgrade: `helm upgrade lab10-release k8s/devops-python -f k8s/devops-python/values-prod.yaml` + + +## Hook Implementation + +### Implementation + +Two Helm hooks were implemented: + +- `pre-install` job for configuration validation +- `post-install` job for smoke testing the deployed service + +Hook execution order: + +- pre-install weight: `-5` +- post-install weight: `5` + +Both hooks use the same deletion policy: + +```yaml +"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded +``` + +This ensures that successful hook jobs are removed automatically and old hook jobs do not block future installs. + +### Hook Evidence + +#### Pre-install Hook + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get jobs +NAME STATUS COMPLETIONS DURATION AGE +lab10-release-devops-python-pre-install Complete 1/1 13s 13s +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl logs job/lab10-release-devops-python-pre-install +Pre-install validation passed for s3rap1s/devops-info-service:v2 +``` + +#### Post-install Hook + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get jobs +NAME STATUS COMPLETIONS DURATION AGE +lab10-release-devops-python-post-install Running 0/1 11s 11s +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl describe job lab10-release-devops-python-post-install +Name: lab10-release-devops-python-post-install +Namespace: default +Selector: batch.kubernetes.io/controller-uid=0b5c2b5d-e3f8-47fd-b934-cfa34a4cd100 +Labels: app.kubernetes.io/instance=lab10-release + app.kubernetes.io/managed-by=Helm + app.kubernetes.io/name=devops-python + app.kubernetes.io/version=2.0.0 + helm.sh/chart=devops-python-0.1.0 +Annotations: helm.sh/hook: post-install + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded + helm.sh/hook-weight: 5 +Parallelism: 1 +Completions: 1 +Completion Mode: NonIndexed +Suspend: false +Backoff Limit: 0 +Start Time: Wed, 01 Apr 2026 15:22:01 +0300 +Pods Statuses: 1 Active (1 Ready) / 0 Succeeded / 0 Failed +Pod Template: + Labels: app.kubernetes.io/instance=lab10-release + app.kubernetes.io/name=devops-python + batch.kubernetes.io/controller-uid=0b5c2b5d-e3f8-47fd-b934-cfa34a4cd100 + batch.kubernetes.io/job-name=lab10-release-devops-python-post-install + controller-uid=0b5c2b5d-e3f8-47fd-b934-cfa34a4cd100 + job-name=lab10-release-devops-python-post-install + Containers: + post-install-smoke-test: + Image: busybox:1.36.1 + Port: + Host Port: + Command: + sh + -c + wget -qO- http://lab10-release-devops-python:80/health && \ + echo "Post-install smoke test passed" && \ + sleep 10 + + Environment: + Mounts: + Volumes: + Node-Selectors: + Tolerations: +Events: + Type Reason Age From Message + ---- ------ ---- ---- ------- + Normal SuccessfulCreate 11s job-controller Created pod: lab10-release-devops-python-post-install-q48b2 +``` + +#### Hook Deletion Policy Evidence + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get jobs +No resources found in default namespace. +``` + + +## Installation Evidence + +### Installed Releases + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm list +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +lab10-release default 2 2026-04-01 15:22:37.468973619 +0300 MSK deployed devops-python-0.1.0 2.0.0 +``` + +### Development Deployment + +The chart was first installed with `values-dev.yaml`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get all -l app.kubernetes.io/instance=lab10-release +NAME READY STATUS RESTARTS AGE +pod/lab10-release-devops-python-54484c56d7-r2v6f 1/1 Running 0 37s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/lab10-release-devops-python NodePort 10.100.167.57 80:30599/TCP 37s + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/lab10-release-devops-python 1/1 1 1 37s + +NAME DESIRED CURRENT READY AGE +replicaset.apps/lab10-release-devops-python-54484c56d7 1 1 1 37s +``` + +### Production Upgrade + +The same release was upgraded with `values-prod.yaml`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm get values lab10-release +USER-SUPPLIED VALUES: +image: + tag: v2 +livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 30 + periodSeconds: 5 +readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 10 + periodSeconds: 3 +replicaCount: 5 +resources: + limits: + cpu: 500m + memory: 512Mi + requests: + cpu: 200m + memory: 256Mi +service: + type: LoadBalancer +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get all -l app.kubernetes.io/instance=lab10-release +NAME READY STATUS RESTARTS AGE +pod/lab10-release-devops-python-79cc745644-9r8qw 1/1 Running 0 2m44s +pod/lab10-release-devops-python-79cc745644-ccjqv 1/1 Running 0 2m32s +pod/lab10-release-devops-python-79cc745644-m9fjs 1/1 Running 0 2m44s +pod/lab10-release-devops-python-79cc745644-v2drp 1/1 Running 0 2m44s +pod/lab10-release-devops-python-79cc745644-vldzr 1/1 Running 0 2m32s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/lab10-release-devops-python LoadBalancer 10.100.167.57 80:30599/TCP 3m33s + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/lab10-release-devops-python 5/5 5 5 3m33s + +NAME DESIRED CURRENT READY AGE +replicaset.apps/lab10-release-devops-python-54484c56d7 0 0 0 3m33s +replicaset.apps/lab10-release-devops-python-79cc745644 5 5 5 2m44s +``` + + +## Operations + +**Install** - `helm install lab10-release k8s/devops-python -f k8s/devops-python/values-dev.yaml --wait --wait-for-jobs --debug` + +**Upgrade** - `helm upgrade lab10-release k8s/devops-python -f k8s/devops-python/values-prod.yaml --wait --debug` + +**Rollback** - `helm rollback lab10-release 1` + +**Uninstall** - `helm uninstall lab10-release` + + +## Testing & Validation + +### `helm lint` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm lint k8s/devops-python +==> Linting k8s/devops-python +[INFO] Chart.yaml: icon is recommended + +1 chart(s) linted, 0 chart(s) failed +``` + +### `helm template` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm template lab10-release k8s/devops-python -f k8s/devops-python/values-dev.yaml +# Source: devops-python/templates/service.yaml +kind: Service +# Source: devops-python/templates/deployment.yaml +kind: Deployment +# Source: devops-python/templates/post-install-job.yaml +kind: Job +# Source: devops-python/templates/pre-install-job.yaml +kind: Job +``` + +### `helm install --dry-run=client --debug` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm install --dry-run=client --debug lab10-dryrun k8s/devops-python -f k8s/devops-python/values-dev.yaml +NAME: lab10-dryrun +STATUS: pending-install +DESCRIPTION: Dry run complete +HOOKS: +# Source: devops-python/templates/post-install-job.yaml +kind: Job +# Source: devops-python/templates/pre-install-job.yaml +kind: Job +MANIFEST: +# Source: devops-python/templates/service.yaml +kind: Service +# Source: devops-python/templates/deployment.yaml +kind: Deployment +``` + +### Application Accessibility + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get svc lab10-release-devops-python -o wide +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR +lab10-release-devops-python LoadBalancer 10.100.167.57 80:30599/TCP 3m44s app.kubernetes.io/instance=lab10-release,app.kubernetes.io/name=devops-python +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ minikube ip +192.168.49.2 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ curl -s http://192.168.49.2:30599/health +{"status":"healthy","timestamp":"2026-04-01T12:25:32.023915+00:00","uptime_seconds":172} +``` + + +## Bonus: Library Chart + +### Implementation + +For the bonus task, I created a shared library chart in `k8s/common-lib` and a second application chart in `k8s/devops-go`. + +Library chart structure: + +```text +k8s/common-lib/ +├── Chart.yaml +└── templates/ + └── _helpers.tpl +``` + +Shared templates extracted into the library: + +- `common.name` +- `common.fullname` +- `common.chart` +- `common.selectorLabels` +- `common.labels` + +Both application charts use the library as a dependency: + +- `k8s/devops-python` +- `k8s/devops-go` + +Both `Chart.yaml` files now include: + +```yaml +dependencies: + - name: common-lib + version: 0.1.0 + repository: "file://../common-lib" +``` + +This removed duplicated helper logic and gave both charts the same naming and label conventions. + +### Library Usage Evidence + +Rendered output for the Python chart: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm template bonus-python k8s/devops-python +# Source: devops-python/templates/service.yaml +kind: Service + name: bonus-python-devops-python +# Source: devops-python/templates/deployment.yaml +kind: Deployment + name: bonus-python-devops-python +# Source: devops-python/templates/post-install-job.yaml +kind: Job +# Source: devops-python/templates/pre-install-job.yaml +kind: Job +``` + +Rendered output for the Go chart: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm template bonus-go k8s/devops-go +# Source: devops-go/templates/service.yaml +kind: Service + name: bonus-go-devops-go +# Source: devops-go/templates/deployment.yaml +kind: Deployment + name: bonus-go-devops-go +``` + +### Deployment Evidence + +Both charts were installed successfully: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ helm list +bonus-go default 1 2026-04-01 16:15:58.477947427 +0300 MSK deployed devops-go-0.1.0 1.0.0 +bonus-python default 1 2026-04-01 16:15:58.481181983 +0300 MSK deployed devops-python-0.1.0 2.0.0 +``` + +Python chart resources: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get all -l app.kubernetes.io/instance=bonus-python +NAME READY STATUS RESTARTS AGE +pod/bonus-python-devops-python-7595f7674c-4xk62 1/1 Running 0 38s +pod/bonus-python-devops-python-7595f7674c-rdk2c 1/1 Running 0 38s +pod/bonus-python-devops-python-7595f7674c-z24xn 1/1 Running 0 38s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/bonus-python-devops-python NodePort 10.107.222.96 80:32036/TCP 38s + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/bonus-python-devops-python 3/3 3 3 38s +``` + +Go chart resources: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab10 λ kubectl get all -l app.kubernetes.io/instance=bonus-go +NAME READY STATUS RESTARTS AGE +pod/bonus-go-devops-go-6487688d6b-4rjzd 1/1 Running 0 26s +pod/bonus-go-devops-go-6487688d6b-cb96v 1/1 Running 0 26s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/bonus-go-devops-go ClusterIP 10.99.193.94 80/TCP 26s + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/bonus-go-devops-go 2/2 2 2 26s +``` + +### Benefits + +- DRY: one shared source of helper templates instead of duplicated `_helpers.tpl` +- consistency: both charts use the same naming and labeling conventions +- maintainability: helper changes now happen in one library chart instead of multiple application charts diff --git a/k8s/MONITORING.md b/k8s/MONITORING.md new file mode 100644 index 0000000000..53e1bd13f5 --- /dev/null +++ b/k8s/MONITORING.md @@ -0,0 +1,406 @@ +# Lab 16: Kubernetes Monitoring & Init Containers + +## 1. Kube-Prometheus Stack + +### Components + +The monitoring stack was installed with `kube-prometheus-stack`. + +- Prometheus Operator manages Prometheus, Alertmanager, ServiceMonitor, and related CRDs. +- Prometheus stores time series, scrapes Kubernetes and application metrics, and evaluates alert rules. +- Alertmanager receives firing alerts from Prometheus and groups, silences, or routes them. +- Grafana provides dashboards over Prometheus data. +- kube-state-metrics exposes Kubernetes object state, such as pods, deployments, StatefulSets, and PVCs. +- node-exporter exposes node-level CPU, memory, filesystem, and network metrics. + +### Installation + +The chart repository was already configured and then updated. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts +"prometheus-community" already exists with the same configuration, skipping +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ helm repo update prometheus-community +...Successfully got an update from the "prometheus-community" chart repository +Update Complete. ⎈Happy Helming!⎈ +``` + +The admission webhook certificate generator image was loaded into Minikube before installation. This kept admission webhooks enabled while avoiding image pull timeouts from `registry.k8s.io`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ docker pull registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20221220-controller-v1.5.1-58-g787ea74b6 +Status: Downloaded newer image for registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20221220-controller-v1.5.1-58-g787ea74b6 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ minikube image load registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20221220-controller-v1.5.1-58-g787ea74b6 +``` + +Monitoring stack values are stored in `k8s/monitoring-values.yaml`. Admission webhooks and operator TLS are enabled, while operator probe timeouts are increased for local Minikube stability. + +```yaml +prometheusOperator: + admissionWebhooks: + enabled: true + tls: + enabled: true + livenessProbe: + timeoutSeconds: 5 + readinessProbe: + timeoutSeconds: 5 +``` + +The stack was installed with Helm. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ helm upgrade --install monitoring prometheus-community/kube-prometheus-stack --version 65.8.1 --namespace monitoring --create-namespace -f k8s/monitoring-values.yaml --timeout 15m +Release "monitoring" does not exist. Installing it now. +NAME: monitoring +LAST DEPLOYED: Fri May 1 12:45:35 2026 +NAMESPACE: monitoring +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +``` + +All monitoring pods are running and ready. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl get po,svc -n monitoring +NAME READY STATUS RESTARTS AGE +pod/alertmanager-monitoring-kube-prometheus-alertmanager-0 2/2 Running 0 21m +pod/monitoring-grafana-69db76f9b4-lc6s2 3/3 Running 0 22m +pod/monitoring-kube-prometheus-operator-f78b8654c-fkk4r 1/1 Running 0 22m +pod/monitoring-kube-state-metrics-75c9d8f7c7-xv8ch 1/1 Running 0 22m +pod/monitoring-prometheus-node-exporter-rxxgt 1/1 Running 0 22m +pod/prometheus-monitoring-kube-prometheus-prometheus-0 2/2 Running 0 21m + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/alertmanager-operated ClusterIP None 9093/TCP,9094/TCP,9094/UDP 21m +service/monitoring-grafana ClusterIP 10.106.115.37 80/TCP 22m +service/monitoring-kube-prometheus-alertmanager ClusterIP 10.111.243.193 9093/TCP,8080/TCP 22m +service/monitoring-kube-prometheus-operator ClusterIP 10.103.187.7 443/TCP 22m +service/monitoring-kube-prometheus-prometheus ClusterIP 10.107.8.88 9090/TCP,8080/TCP 22m +service/monitoring-kube-state-metrics ClusterIP 10.98.158.78 8080/TCP 22m +service/monitoring-prometheus-node-exporter ClusterIP 10.100.141.3 9100/TCP 22m +service/prometheus-operated ClusterIP None 9090/TCP 21m +``` + +UI access was opened with port forwarding. + +```bash +kubectl port-forward svc/monitoring-grafana -n monitoring 3000:80 +kubectl port-forward svc/monitoring-kube-prometheus-prometheus -n monitoring 9090:9090 +kubectl port-forward svc/monitoring-kube-prometheus-alertmanager -n monitoring 9093:9093 +``` + +The endpoints returned `HTTP/1.1 200 OK`. + + +## 2. Dashboard Answers + +### 1. Pod Resources + +Dashboard: `Kubernetes / Compute Resources / Pod` + +StatefulSet namespace: `lab16` + +Observed pod CPU usage: + +```text +lab16-stateful-devops-python-0 0.00172 cores +lab16-stateful-devops-python-1 0.00186 cores +lab16-stateful-devops-python-2 0.00240 cores +``` + +Observed pod memory working set: + +```text +lab16-stateful-devops-python-0 30.79 MB +lab16-stateful-devops-python-1 30.63 MB +lab16-stateful-devops-python-2 30.60 MB +``` + +![Pod resources](monitoring/screenshots/grafana-pod-resources.png) + +### 2. Default Namespace Pod CPU + +Dashboard: `Kubernetes / Compute Resources / Namespace (Pods)` + +Namespace: `default` + +Top CPU users: + +```text +vault-0 0.02895 cores +vault-agent-injector-848dd747d7-lvs5l 0.00347 cores +lab10-release-devops-python-79cc745644-vldzr 0.00282 cores +lab10-release-devops-python-79cc745644-ccjqv 0.00277 cores +lab10-release-devops-python-79cc745644-9r8qw 0.00254 cores +``` + +Lowest non-zero CPU users: + +```text +bonus-go-devops-go-6487688d6b-cb96v 0.00024 cores +devops-go-845d5f465d-fl9ml 0.00027 cores +devops-go-845d5f465d-xtkjg 0.00029 cores +devops-go-845d5f465d-2zkv8 0.00034 cores +bonus-go-devops-go-6487688d6b-4rjzd 0.00034 cores +``` + +![Default namespace pods](monitoring/screenshots/grafana-default-namespace-pods.png) + +### 3. Node Metrics + +Dashboard: `Node Exporter / Nodes` + +Node: `minikube` + +Observed values: + +```text +CPU cores: 12 +CPU usage: 18.55% +Memory usage: 58.04% +Memory used: 9106.50 MB +``` + +![Node exporter](monitoring/screenshots/grafana-node-exporter.png) + +### 4. Kubelet + +Dashboard: `Kubernetes / Kubelet` + +Observed kubelet values: + +```text +Running pods: 69 +Running containers: 73 +Exited containers tracked: 99 +Unknown containers tracked: 2 +Created containers tracked: 1 +``` + +![Kubelet](monitoring/screenshots/grafana-kubelet.png) + +### 5. Network + +Dashboard: `Kubernetes / Networking / Namespace (Pods)` + +Namespace: `default` + +The pod-level networking dashboard showed `No data`. Prometheus confirmed that `container_network_*` metrics are not present in this Minikube setup: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ curl -sG http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=count({__name__=~"container_network_.*"})' +{"status":"success","data":{"resultType":"vector","result":[]}} +``` + +Node-level network metrics are available from node-exporter: + +```text +receive bridge 19706.09 B/s +receive eth0 2315.17 B/s +receive lo 64375.03 B/s +transmit bridge 51536.03 B/s +transmit eth0 1151.88 B/s +transmit lo 64375.03 B/s +``` + +![Default namespace network](monitoring/screenshots/grafana-network-default.png) + +### 6. Alerts + +Alertmanager UI: `http://localhost:9093` + +Prometheus reported 11 firing alerts during the check. + +```text +Watchdog +etcdInsufficientMembers +TargetDown +TargetDown +etcdMembersDown +TargetDown +KubeControllerManagerDown +KubeSchedulerDown +KubePodNotReady +KubeDeploymentReplicasMismatch +NodeMemoryMajorPagesFaults +``` + +![Alertmanager alerts](monitoring/screenshots/alertmanager-alerts.png) + + +## 3. Init Containers + +The Helm chart now supports optional init containers through `initContainers` values. + +`k8s/devops-python/values-monitoring.yaml` enables two patterns: + +- `wait-for-service`: waits until Grafana service is resolvable +- `init-download`: downloads the Grafana login page into a shared `emptyDir` + +```yaml +initContainers: + enabled: true + sharedMountPath: /init-data + waitForService: + enabled: true + image: busybox:1.36.1 + host: monitoring-grafana.monitoring.svc.cluster.local + download: + enabled: true + image: busybox:1.36.1 + url: http://monitoring-grafana.monitoring.svc/login + outputFile: grafana-login.html +``` + +The Lab 16 app release was installed into `lab16`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl create namespace lab16 +namespace/lab16 created +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ helm upgrade --install lab16-stateful k8s/devops-python -n lab16 -f k8s/devops-python/values-monitoring.yaml --timeout 10m +Release "lab16-stateful" does not exist. Installing it now. +NAME: lab16-stateful +LAST DEPLOYED: Fri May 1 12:46:57 2026 +NAMESPACE: lab16 +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None +``` + +The StatefulSet became ready. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl rollout status statefulset/lab16-stateful-devops-python -n lab16 --timeout=300s +statefulset rolling update complete 3 pods at revision lab16-stateful-devops-python-65c996cf79... +``` + +Resource verification: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl get po,sts,svc,pvc,servicemonitor -n lab16 -l app.kubernetes.io/instance=lab16-stateful +NAME READY STATUS RESTARTS AGE +pod/lab16-stateful-devops-python-0 1/1 Running 0 50s +pod/lab16-stateful-devops-python-1 1/1 Running 0 38s +pod/lab16-stateful-devops-python-2 1/1 Running 0 27s + +NAME READY AGE +statefulset.apps/lab16-stateful-devops-python 3/3 50s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/lab16-stateful-devops-python NodePort 10.102.214.1 80:32160/TCP 50s +service/lab16-stateful-devops-python-headless ClusterIP None 80/TCP 50s + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE +persistentvolumeclaim/data-volume-lab16-stateful-devops-python-0 Bound pvc-f02d11b8-2082-4052-a24d-c3537db0a67e 100Mi RWO standard 50s +persistentvolumeclaim/data-volume-lab16-stateful-devops-python-1 Bound pvc-be6365d6-c2c6-489f-a3f5-8c75e8ecc3f1 100Mi RWO standard 38s +persistentvolumeclaim/data-volume-lab16-stateful-devops-python-2 Bound pvc-7fb951c1-f645-415a-9b38-96b011d6c618 100Mi RWO standard 27s + +NAME AGE +servicemonitor.monitoring.coreos.com/lab16-stateful-devops-python 50s +``` + +The wait init container resolved the dependency service: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl logs lab16-stateful-devops-python-0 -n lab16 -c wait-for-service +Server: 10.96.0.10 +Address: 10.96.0.10:53 + +Name: monitoring-grafana.monitoring.svc.cluster.local +Address: 10.106.115.37 +``` + +The download init container saved a file into the shared volume: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl logs lab16-stateful-devops-python-0 -n lab16 -c init-download +Connecting to monitoring-grafana.monitoring.svc (10.106.115.37:80) +saving to '/init-data/grafana-login.html' +grafana-login.html 100% |********************************| 44874 0:00:00 ETA +'/init-data/grafana-login.html' saved +``` + +The main container can read the downloaded file: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ kubectl exec lab16-stateful-devops-python-0 -n lab16 -- sh -c 'ls -l /init-data/grafana-login.html && head -n 3 /init-data/grafana-login.html' +Defaulted container "app" out of: app, volume-permissions (init), wait-for-service (init), init-download (init) +-rw-r--r-- 1 root root 44874 May 1 09:47 /init-data/grafana-login.html + + + +``` + + +## 4. Custom Metrics Bonus + +The Python application already exposes `/metrics` using the Prometheus client library. + +The Helm chart now renders a `ServiceMonitor` when `.Values.serviceMonitor.enabled` is true. + +```yaml +serviceMonitor: + enabled: true + labels: + release: monitoring + interval: 15s + scrapeTimeout: 10s + path: /metrics +``` + +Rendered ServiceMonitor: + +```yaml +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + labels: + release: monitoring + name: lab16-stateful-devops-python + namespace: lab16 +spec: + endpoints: + - interval: 15s + path: /metrics + port: http + scrapeTimeout: 10s + selector: + matchLabels: + app.kubernetes.io/instance: lab16-stateful + app.kubernetes.io/name: devops-python +``` + +Prometheus target check: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ curl -sG http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=up{namespace="lab16"}' +lab16-stateful-devops-python-headless lab16-stateful-devops-python-0 1 +lab16-stateful-devops-python lab16-stateful-devops-python-1 1 +lab16-stateful-devops-python-headless lab16-stateful-devops-python-1 1 +lab16-stateful-devops-python lab16-stateful-devops-python-0 1 +lab16-stateful-devops-python-headless lab16-stateful-devops-python-2 1 +lab16-stateful-devops-python lab16-stateful-devops-python-2 1 +``` + +Custom application metric: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab16 λ curl -sG http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=sum(devops_info_endpoint_calls_total{namespace="lab16"}) by (pod, endpoint)' +lab16-stateful-devops-python-0 http 1386 +lab16-stateful-devops-python-1 http 1378 +lab16-stateful-devops-python-2 http 1371 +``` + +![Prometheus Lab 16 metrics](monitoring/screenshots/prometheus-lab16-metrics.png) diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 0000000000..d83f2f8051 --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,644 @@ +# Lab 9 - Kubernetes Fundamentals + +## 1. Architecture Overview +```mermaid +flowchart LR + User[Client] --> NodePort[NodePort Service
devops-python-service:80] + NodePort --> Pod1[Pod 1
devops-python] + NodePort --> Pod2[Pod 2
devops-python] + NodePort --> Pod3[Pod 3
devops-python] + NodePort --> Pod4[Pod 4
devops-python] + NodePort --> Pod5[Pod 5
devops-python] +``` + +### Networking Flow + +- The client sends traffic to the `minikube` node IP and the assigned `NodePort`. +- The `devops-python-service` forwards traffic to pods with label `app=devops-python`. +- Each pod exposes the Flask application on container port `5000`. +- Health and metrics endpoints are available as `/health` and `/metrics`. + +### Resource Allocation Strategy + +Each application pod is configured with: + +- CPU request: `100m` +- CPU limit: `200m` +- Memory request: `128Mi` +- Memory limit: `256Mi` + +This keeps scheduling predictable and prevents one pod from consuming excessive node resources. + +## 2. Cluster Setup + +I used `minikube` because it is simple to start locally and is well suited for testing Deployments, Services, NodePort access, scaling, and rolling updates. + +### `kubectl cluster-info` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl cluster-info +Kubernetes control plane is running at https://192.168.49.2:8443 +CoreDNS is running at https://192.168.49.2:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy + +To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'. +``` + +### `kubectl get nodes` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get nodes +NAME STATUS ROLES AGE VERSION +minikube Ready control-plane 101s v1.35.1 +``` + + +## 3. Manifest Files + +### `k8s/deployment.yml` + +This manifest defines the `Deployment` for `devops-python`. + +Key choices: + +- `replicas`: started with 3 replicas, later scaled to 5 for Task 4 +- `strategy.type: RollingUpdate` +- `maxSurge: 1` +- `maxUnavailable: 0` +- `livenessProbe` and `readinessProbe` using `/health` +- resource requests and limits for CPU and memory +- image: `s3rap1s/devops-info-service:latest` + +Justification: + +- 3 replicas satisfy the minimum Task 2 requirement. +- 5 replicas were used later to demonstrate scaling. +- `maxUnavailable: 0` helps preserve availability during updates. +- `/health` is the simplest reliable probe endpoint already implemented by the app. +- resource requests and limits reflect a small web service running in a local cluster. + +### `k8s/service.yml` + +Key choices: + +- `type: NodePort` +- selector: `app: devops-python` +- service port: `80` +- target port: `5000` + +Justification: + +- `NodePort` is appropriate for local cluster testing. +- the selector matches the `Deployment` labels exactly +- the service exposes a simple HTTP entry point while forwarding to the Flask container port + +## 4. Deployment +### 4.1 Deploy the main application + +The Deployment was created from `k8s/deployment.yml` with 3 initial replicas. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get deployments +NAME READY UP-TO-DATE AVAILABLE AGE +devops-python 0/3 3 0 9s +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get pods +NAME READY STATUS RESTARTS AGE +devops-python-9db5545cf-tfqwh 0/1 ContainerCreating 0 13s +devops-python-9db5545cf-vvvm2 0/1 ContainerCreating 0 13s +devops-python-9db5545cf-whgxm 0/1 ContainerCreating 0 13s +``` + +### 4.2 Expose the application with a NodePort Service + +The Service was created from `k8s/service.yml` and exposed the app through a stable node port. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get services +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +devops-python-service NodePort 10.104.34.133 80:30243/TCP 6s +kubernetes ClusterIP 10.96.0.1 443/TCP 8m2s +``` + +### 4.3 Verify the application through the Service + +The application was then accessed through the Minikube node IP and the assigned `NodePort`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ curl http://192.168.49.2:30243/health +{"status":"healthy","timestamp":"2026-03-25T09:19:27.861595+00:00","uptime_seconds":218} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ curl http://192.168.49.2:30243/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"} 286.0 +python_gc_objects_collected_total{generation="1"} 70.0 +python_gc_objects_collected_total{generation="2"} 0.0 +... +``` + + +### 4.4 Re-apply the Deployment and confirm running pods + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl apply -f k8s/deployment.yml +deployment.apps/devops-python configured +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get pods +NAME READY STATUS RESTARTS AGE +devops-python-9db5545cf-csh4w 1/1 Running 0 24s +devops-python-9db5545cf-f4f28 1/1 Running 0 24s +devops-python-9db5545cf-tfqwh 1/1 Running 0 6m5s +devops-python-9db5545cf-vvvm2 1/1 Running 0 6m5s +devops-python-9db5545cf-whgxm 1/1 Running 0 6m5s +``` + +### 4.5 Scale the Deployment to 5 replicas and inspect the resources + +After scaling, the cluster showed five running pods for the Deployment. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get pods +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +pod/devops-python-9db5545cf-f6jl5 1/1 Running 0 6m59s 10.244.0.16 minikube +pod/devops-python-9db5545cf-jwj65 1/1 Running 0 7m9s 10.244.0.15 minikube +pod/devops-python-9db5545cf-lm8tn 1/1 Running 0 7m31s 10.244.0.13 minikube +pod/devops-python-9db5545cf-q2n6w 1/1 Running 0 7m20s 10.244.0.14 minikube +pod/devops-python-9db5545cf-s9vnc 1/1 Running 0 6m50s 10.244.0.17 minikube +s3rap1s in ~/devops/DevOps-Core-Course on lab09 λ kubectl get services +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR +service/devops-python-service NodePort 10.104.34.133 80:30243/TCP 35m app=devops-python +service/kubernetes ClusterIP 10.96.0.1 443/TCP 43m +``` + +The Deployment description confirmed the rolling strategy, probes, resource limits, and the final replica count: + +```bash +Name: devops-python +Namespace: default +CreationTimestamp: Wed, 25 Mar 2026 12:15:17 +0300 +Labels: app=devops-python +Annotations: deployment.kubernetes.io/revision: 3 +Selector: app=devops-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=devops-python + Containers: + app: + Image: s3rap1s/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=15s timeout=1s period=10s #success=1 #failure=3 + Readiness: http-get http://:5000/health delay=5s timeout=1s period=5s #success=1 #failure=3 + Environment: + PORT: 5000 + HOST: 0.0.0.0 + Mounts: + Volumes: + Node-Selectors: + Tolerations: +Conditions: + Type Status Reason + ---- ------ ------ + Available True MinimumReplicasAvailable + Progressing True NewReplicaSetAvailable +OldReplicaSets: devops-python-8cc7694d6 (0/0 replicas created) +NewReplicaSet: devops-python-9db5545cf (5/5 replicas created) +Events: + Type Reason Age From Message + ---- ------ ---- ---- ------- + Normal ScalingReplicaSet 50m deployment-controller Scaled up replica set devops-python-9db5545cf from 0 to 3 + Normal ScalingReplicaSet 44m deployment-controller Scaled up replica set devops-python-9db5545cf from 3 to 5 + Normal ScalingReplicaSet 32m deployment-controller Scaled up replica set devops-python-8cc7694d6 from 0 to 1 + Normal ScalingReplicaSet 32m deployment-controller Scaled down replica set devops-python-9db5545cf from 5 to 4 + Normal ScalingReplicaSet 32m deployment-controller Scaled up replica set devops-python-8cc7694d6 from 1 to 2 + Normal ScalingReplicaSet 31m deployment-controller Scaled down replica set devops-python-9db5545cf from 4 to 3 + Normal ScalingReplicaSet 31m deployment-controller Scaled up replica set devops-python-8cc7694d6 from 2 to 3 + Normal ScalingReplicaSet 31m deployment-controller Scaled down replica set devops-python-9db5545cf from 3 to 2 + Normal ScalingReplicaSet 31m deployment-controller Scaled up replica set devops-python-8cc7694d6 from 3 to 4 + Normal ScalingReplicaSet 31m deployment-controller Scaled down replica set devops-python-9db5545cf from 2 to 1 + Normal ScalingReplicaSet 31m deployment-controller Scaled up replica set devops-python-8cc7694d6 from 4 to 5 + Normal ScalingReplicaSet 19m (x11 over 31m) deployment-controller (combined from similar events): Scaled down replica set devops-python-8cc7694d6 from 1 to 0 +``` + +Full resource state: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get all +NAME READY STATUS RESTARTS AGE +pod/devops-python-9db5545cf-f6jl5 1/1 Running 0 101s +pod/devops-python-9db5545cf-jwj65 1/1 Running 0 111s +pod/devops-python-9db5545cf-lm8tn 1/1 Running 0 2m13s +pod/devops-python-9db5545cf-q2n6w 1/1 Running 0 2m2s +pod/devops-python-9db5545cf-s9vnc 1/1 Running 0 92s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/devops-python-service NodePort 10.104.34.133 80:30243/TCP 29m +service/kubernetes ClusterIP 10.96.0.1 443/TCP 37m + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/devops-python 5/5 5 5 31m + +NAME DESIRED CURRENT READY AGE +replicaset.apps/devops-python-8cc7694d6 0 0 0 14m +replicaset.apps/devops-python-9db5545cf 5 5 5 31m +``` + +### 4.6 Perform a rolling update + +To initiate a rolling update, the image tag in `deployment.yml` was changed from `s3rap1s/devops-info-service:latest` to `s3rap1s/devops-info-service:v2` and the manifest was reapplied. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl apply -f k8s/deployment.yml +deployment.apps/devops-python configured +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl describe deployment devops-python | grep Image +Image: s3rap1s/devops-info-service:v2 +``` + +Kubernetes then rolled out the update gradually: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl rollout status deployment devops-python +Waiting for deployment "devops-python" rollout to finish: 1 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 1 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 1 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 2 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 2 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 2 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 3 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 3 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 3 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 1 old replicas are pending termination... +Waiting for deployment "devops-python" rollout to finish: 1 old replicas are pending termination... +Waiting for deployment "devops-python" rollout to finish: 1 old replicas are pending termination... +deployment "devops-python" successfully rolled out +``` + +During replacement, old and new pods coexisted: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get pods +NAME READY STATUS RESTARTS AGE +devops-python-8cc7694d6-2dwc2 1/1 Terminating 0 12m +devops-python-8cc7694d6-7545c 1/1 Terminating 0 12m +devops-python-8cc7694d6-hsn2j 1/1 Terminating 0 12m +devops-python-9db5545cf-f6jl5 1/1 Running 0 30s +devops-python-9db5545cf-jwj65 1/1 Running 0 40s +devops-python-9db5545cf-lm8tn 1/1 Running 0 62s +devops-python-9db5545cf-q2n6w 1/1 Running 0 51s +devops-python-9db5545cf-s9vnc 1/1 Running 0 21s +``` + + +### 4.7 Demonstrate rollback capability + +The rollout history showed multiple revisions: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl rollout history deployment devops-python +deployment.apps/devops-python +REVISION CHANGE-CAUSE +1 +2 +``` + +The rollback was then executed: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl rollout undo deployment devops-python +deployment.apps/devops-python rolled back +``` + +Rollback progress: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl rollout status deployment devops-python +Waiting for deployment "devops-python" rollout to finish: 1 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 1 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 1 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 2 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 2 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 2 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 3 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 3 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 3 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 4 out of 5 new replicas have been updated... +Waiting for deployment "devops-python" rollout to finish: 1 old replicas are pending termination... +Waiting for deployment "devops-python" rollout to finish: 1 old replicas are pending termination... +deployment "devops-python" successfully rolled out +``` + +History after rollback: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl rollout history deployment devops-python +deployment.apps/devops-python +REVISION CHANGE-CAUSE +1 +2 +``` + +This confirms that rollback capability was not only available but actually demonstrated in practice. + +## 5. Production Considerations + +### Health Checks + +The Deployment uses: + +- `readinessProbe` on `/health` - readiness ensures traffic is sent only to healthy pods +- `livenessProbe` on `/health` - liveness allows Kubernetes to restart unhealthy containers automatically + +### Resource Limits + +Configured values: + +- requests: `100m CPU`, `128Mi memory` - requests help the scheduler place pods reliably +- limits: `200m CPU`, `256Mi memory` - limits prevent resource starvation on the node + + +### How This Could Be Improved for Production + +- use immutable image tags instead of `latest` +- add a proper `startupProbe` +- set `imagePullPolicy` explicitly +- use Horizontal Pod Autoscaler +- use separate namespaces for environments + +### Monitoring and Observability Strategy + +For production, this deployment should be integrated with: + +- Prometheus for metrics scraping +- Grafana for dashboards +- Loki/Promtail for centralized logs +- alerts for pod restarts, high latency, and failed readiness checks + +The application already exposes `/metrics`, which makes future Kubernetes monitoring integration straightforward. + +## 6. Challenges & Solutions + +### Challenge 1: Verifying Rolling Update Behavior + +This was debugged with: + +- `kubectl rollout status deployment devops-python` +- `kubectl get pods` +- `kubectl describe deployment devops-python` + +The rollout status output and Deployment events showed that Kubernetes created new pods gradually and terminated old ones only after the new pods became available. + +## 7. Bonus Task: Ingress with TLS + +The bonus implementation uses the existing Python application as `app1` and the Go application as `app2`. + +### Bonus Manifests + +- `k8s/go-deployment.yml` - Deployment for the Go application +- `k8s/go-service.yml` - Service for the Go application +- `k8s/ingress.yml` - Ingress with path-based routing and TLS + +### Routing Design + +- `/app1` -> `devops-python-service` +- `/app2` -> `devops-go-service` + +Both applications serve content on `/`, so the Ingress uses NGINX rewrite annotations to strip `/app1` and `/app2` before forwarding the request upstream. + +#### 7.1 Build and push the Go image + +The second application for `/app2` is the Go version of the service, so its image was built and pushed to Docker Hub first. + +#### 7.2 Enable the Ingress controller + +The `ingress` addon was enabled in Minikube and the controller pods were verified in the `ingress-nginx` namespace. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ minikube addons enable ingress +💡 ingress is an addon maintained by Kubernetes. For any concerns contact minikube on GitHub. +You can view the list of minikube maintainers at: https://github.com/kubernetes/minikube/blob/master/OWNERS + ▪ Using image registry.k8s.io/ingress-nginx/kube-webhook-certgen:v1.6.7 + ▪ Using image registry.k8s.io/ingress-nginx/kube-webhook-certgen:v1.6.7 + ▪ Using image registry.k8s.io/ingress-nginx/controller:v1.14.3 +🔎 Verifying ingress addon... +🌟 The 'ingress' addon is enabled +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get pods -n ingress-nginx +NAME READY STATUS RESTARTS AGE +ingress-nginx-admission-create-p5mdg 0/1 Completed 0 2m56s +ingress-nginx-admission-patch-cl588 0/1 Completed 0 2m56s +ingress-nginx-controller-596f8778bc-8k48m 1/1 Running 0 2m56s +``` + +#### 7.3 Generate a self-signed certificate and create the TLS secret + +The certificate and private key were generated locally with `openssl`, then the Kubernetes TLS secret was created from those files. + +```bash +openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout tls.key -out tls.crt \ + -subj "/CN=local.example.com/O=local.example.com" +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl create secret tls tls-secret --key tls.key --cert tls.crt +secret/tls-secret created +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get secret tls-secret +NAME TYPE DATA AGE +tls-secret kubernetes.io/tls 2 9s +``` + +#### 7.4 Deploy the second application and its service + +The Go-based application was deployed as a separate `Deployment` and exposed internally through a `ClusterIP` service. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl apply -f k8s/go-deployment.yml +deployment.apps/devops-go created +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl apply -f k8s/go-service.yml +service/devops-go-service created +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get deployments +NAME READY UP-TO-DATE AVAILABLE AGE +devops-go 3/3 3 3 82s +devops-python 5/5 5 5 82m +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get pods +NAME READY STATUS RESTARTS AGE +devops-go-845d5f465d-2zkv8 1/1 Running 0 94s +devops-go-845d5f465d-fl9ml 1/1 Running 0 94s +devops-go-845d5f465d-xtkjg 1/1 Running 0 94s +devops-python-9db5545cf-f6jl5 1/1 Running 0 52m +devops-python-9db5545cf-jwj65 1/1 Running 0 52m +devops-python-9db5545cf-lm8tn 1/1 Running 0 53m +devops-python-9db5545cf-q2n6w 1/1 Running 0 52m +devops-python-9db5545cf-s9vnc 1/1 Running 0 52m +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get services +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +devops-go-service ClusterIP 10.102.215.65 80/TCP 34s +devops-python-service NodePort 10.104.34.133 80:30243/TCP 80m +kubernetes ClusterIP 10.96.0.1 443/TCP 88m +``` + +#### 7.5 Add the local hostname and apply the Ingress + +The local hostname was mapped to the Minikube IP and the Ingress resource was applied. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ echo "$(minikube ip) local.example.com" | sudo tee -a /etc/hosts +192.168.49.2 local.example.com +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl apply -f k8s/ingress.yml +ingress.networking.k8s.io/devops-apps-ingress created +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get ingress +NAME CLASS HOSTS ADDRESS PORTS AGE +devops-apps-ingress nginx local.example.com 80, 443 11s +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl describe ingress devops-apps-ingress +Name: devops-apps-ingress +Labels: +Namespace: default +Address: +Ingress Class: nginx +Default backend: +TLS: + tls-secret terminates local.example.com +Rules: + Host Path Backends + ---- ---- -------- + local.example.com + /app1(/|$)(.*) devops-python-service:80 (10.244.0.13:5000,10.244.0.14:5000,10.244.0.15:5000 + 2 more...) + /app2(/|$)(.*) devops-go-service:80 (10.244.0.21:5000,10.244.0.22:5000,10.244.0.23:5000) +Annotations: nginx.ingress.kubernetes.io/rewrite-target: /$2 + nginx.ingress.kubernetes.io/use-regex: true +Events: + Type Reason Age From Message + ---- ------ ---- ---- ------- + Normal Sync 20s nginx-ingress-controller Scheduled for sync +``` + +#### 7.6 Verify HTTP redirect and HTTPS routing + +The initial HTTP requests were redirected to HTTPS by the Ingress controller, which is expected when TLS is configured. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ curl http://local.example.com/app1 + +308 Permanent Redirect + +

308 Permanent Redirect

+
nginx
+ + +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ curl http://local.example.com/app2 + +308 Permanent Redirect + +

308 Permanent Redirect

+
nginx
+ + +``` + +HTTPS request to `/app1` reached the Python service: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ curl -k https://local.example.com/app1 +{"endpoints":[{"description":"Service information","method":"GET","path":"/"},{"description":"Health check","method":"GET","path":"/health"},{"description":"Prometheus metrics","method":"GET","path":"/metrics"}],"request":{"client_ip":"10.244.0.20","method":"GET","path":"/","user_agent":"curl/8.18.0"},"runtime":{"current_time":"2026-03-25T10:39:48.528453+00:00","timezone":"UTC","uptime_human":"0 hours, 54 minutes","uptime_seconds":3271},"service":{"description":"DevOps course info service","framework":"Flask","name":"devops-info-service","version":"1.0.0"},"system":{"architecture":"x86_64","cpu_count":12,"hostname":"devops-python-9db5545cf-f6jl5","platform":"Linux","platform_version":"6.18.9-arch1-2","python_version":"3.13.12"}} +``` + +HTTPS request to `/app2` reached the Go service: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ curl -k https://local.example.com/app2 +{"service":{"name":"devops-info-service","version":"1.0.0","description":"DevOps course info service","framework":"Go"},"system":{"hostname":"devops-go-845d5f465d-fl9ml","platform":"linux","platform_version":"Linux Kernel","architecture":"amd64","cpu_count":12,"go_version":"go1.21.13"},"runtime":{"uptime_seconds":220,"uptime_human":"0 hours, 3 minutes","current_time":"2026-03-25T10:39:53Z","timezone":"UTC"},"request":{"client_ip":"10.244.0.20:44866","user_agent":"curl/8.18.0","method":"GET","path":"/"},"endpoints":[{"path":"/","method":"GET","description":"Service information"},{"path":"/health","method":"GET","description":"Health check"}]} +``` + +#### 7.7 Resource state + +The final state confirms that both applications, the Ingress resource, and the TLS secret exist and are operational. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get all +NAME READY STATUS RESTARTS AGE +pod/devops-go-845d5f465d-2zkv8 1/1 Running 0 3m59s +pod/devops-go-845d5f465d-fl9ml 1/1 Running 0 3m59s +pod/devops-go-845d5f465d-xtkjg 1/1 Running 0 3m59s +pod/devops-python-9db5545cf-f6jl5 1/1 Running 0 54m +pod/devops-python-9db5545cf-jwj65 1/1 Running 0 55m +pod/devops-python-9db5545cf-lm8tn 1/1 Running 0 55m +pod/devops-python-9db5545cf-q2n6w 1/1 Running 0 55m +pod/devops-python-9db5545cf-s9vnc 1/1 Running 0 54m + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/devops-go-service ClusterIP 10.102.215.65 80/TCP 2m46s +service/devops-python-service NodePort 10.104.34.133 80:30243/TCP 83m +service/kubernetes ClusterIP 10.96.0.1 443/TCP 91m + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/devops-go 3/3 3 3 3m59s +deployment.apps/devops-python 5/5 5 5 84m + +NAME DESIRED CURRENT READY AGE +replicaset.apps/devops-go-845d5f465d 3 3 3 3m59s +replicaset.apps/devops-python-8cc7694d6 0 0 0 67m +replicaset.apps/devops-python-9db5545cf 5 5 5 84m +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get ingress +NAME CLASS HOSTS ADDRESS PORTS AGE +devops-apps-ingress nginx local.example.com 192.168.49.2 80, 443 102s +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab09 ● λ kubectl get secret tls-secret +NAME TYPE DATA AGE +tls-secret kubernetes.io/tls 2 2m8s +``` diff --git a/k8s/ROLLOUTS.md b/k8s/ROLLOUTS.md new file mode 100644 index 0000000000..a87548e621 --- /dev/null +++ b/k8s/ROLLOUTS.md @@ -0,0 +1,486 @@ +# Lab 14: Progressive Delivery with Argo Rollouts + +## 1. Argo Rollouts Setup + +### Installation Verification + +Argo Rollouts controller and dashboard were installed into the `argo-rollouts` namespace. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl get pods -n argo-rollouts -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +argo-rollouts-5f64f8d68-tkwj7 1/1 Running 0 24m 10.244.1.15 minikube +argo-rollouts-dashboard-b79c648c8-x4mql 1/1 Running 0 16m 10.244.1.22 minikube +``` + +The kubectl plugin was installed locally. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts version +kubectl-argo-rollouts: v1.8.3+49fa151 + BuildDate: 2025-06-04T22:15:54Z + GitCommit: 49fa1516cf71672b69e265267da4e1d16e1fe114 + GitTreeState: clean + GoVersion: go1.23.9 + Compiler: gc + Platform: linux/amd64 +``` + +The dashboard was exposed locally with port forwarding: + +```bash +kubectl port-forward svc/argo-rollouts-dashboard -n argo-rollouts 3101:3100 +``` + +The UI is available at `http://localhost:3101/rollouts`. + +### Rollout vs Deployment + +The Helm chart now renders an Argo Rollouts `Rollout` instead of a Kubernetes `Deployment`. + +Main differences: + +- `apiVersion` changed from `apps/v1` to `argoproj.io/v1alpha1` +- `kind` changed from `Deployment` to `Rollout` +- the pod template, selector, probes, volumes, ConfigMaps, Secrets, and PVC usage stayed the same +- `spec.strategy` now supports `canary`, `blueGreen`, pauses, promotion, abort, and analysis steps + + +## 2. Canary Deployment + +### Implementation + +The deployment template was replaced with `k8s/devops-python/templates/rollout.yaml`. The default rollout strategy is canary and is configured in `k8s/devops-python/values.yaml`. + +```yaml +rollout: + strategy: canary + canary: + maxSurge: 25% + maxUnavailable: 0 + steps: + - setWeight: 20 + - pause: {} + - setWeight: 40 + - pause: + duration: 30s + - setWeight: 60 + - pause: + duration: 30s + - setWeight: 80 + - pause: + duration: 30s + - setWeight: 100 +``` + +This matches the required flow: + +- 20% canary traffic with manual promotion +- 40%, 60%, and 80% with 30 second pauses +- 100% after automatic progression + +The canary test values are stored in: + +- `k8s/devops-python/values-canary.yaml` +- `k8s/devops-python/values-canary-update.yaml` + +### Rollout Test + +Initial canary release: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ helm upgrade --install lab14-canary k8s/devops-python -n lab14 -f k8s/devops-python/values-canary.yaml --timeout 10m +Release "lab14-canary" does not exist. Installing it now. +NAME: lab14-canary +LAST DEPLOYED: Sat Apr 25 15:29:26 2026 +NAMESPACE: lab14 +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None +``` + +Config update that triggered a rollout: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ helm upgrade lab14-canary k8s/devops-python -n lab14 -f k8s/devops-python/values-canary-update.yaml --timeout 10m +Release "lab14-canary" has been upgraded. Happy Helming! +NAME: lab14-canary +LAST DEPLOYED: Sat Apr 25 15:29:48 2026 +NAMESPACE: lab14 +STATUS: deployed +REVISION: 2 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +The rollout paused at the first manual step with 20% canary traffic. + +```text +Status: Paused +Message: CanaryPauseStep +Step: 1/9 +SetWeight: 20 +ActualWeight: 20 +``` + +Manual promotion was executed with: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts promote lab14-canary-devops-python -n lab14 +rollout 'lab14-canary-devops-python' promoted +``` + +After promotion, the rollout progressed through the timed pauses and finished healthy. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts get rollout lab14-canary-devops-python -n lab14 +Name: lab14-canary-devops-python +Namespace: lab14 +Status: ✔ Healthy +Strategy: Canary + Step: 9/9 + SetWeight: 100 + ActualWeight: 100 +Images: s3rap1s/devops-info-service:v2 (stable) +Replicas: + Desired: 5 + Current: 5 + Updated: 5 + Ready: 5 + Available: 5 +``` + +### Abort Test + +A new config update was started and then aborted during the rollout. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts abort lab14-canary-devops-python -n lab14 +rollout 'lab14-canary-devops-python' aborted +``` + +The aborted revision was scaled down and traffic returned to the stable ReplicaSet. + +```text +Status: Degraded +Message: RolloutAborted: Rollout aborted update to revision 3 +Step: 0/9 +SetWeight: 0 +ActualWeight: 0 +revision 3: ScaledDown +revision 2: stable +``` + +The release was restored with Helm rollback: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ helm rollback lab14-canary 2 -n lab14 --timeout 10m +Rollback was a success! Happy Helming! +``` + +### Dashboard Evidence + +Canary rollout overview: + +![Canary rollout overview](argocd/screenshots/argo-rollout-main.png) + +Canary rollout details during progression: + +![Canary rollout details](argocd/screenshots/argo-rollout-details.png) + +Canary rollout details after progression: + +![Canary rollout details](argocd/screenshots/argo-rollout-details-final.png) + + +## 3. Blue-Green Deployment + +### Implementation + +Blue-green deployment is configured through separate values files: + +- `k8s/devops-python/values-bluegreen.yaml` +- `k8s/devops-python/values-bluegreen-update.yaml` + +The strategy uses an active service for current traffic and a preview service for the new version. + +```yaml +rollout: + strategy: blueGreen + blueGreen: + autoPromotionEnabled: false + autoPromotionSeconds: null + scaleDownDelaySeconds: 30 + previewReplicaCount: 2 + previewService: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: 32091 +``` + +Services: + +- active: `lab14-bluegreen-devops-python`, NodePort `32090` +- preview: `lab14-bluegreen-devops-python-preview`, NodePort `32091` + +For blue-green releases, Helm does not manage service selectors. Argo Rollouts owns those selectors and switches them between ReplicaSets during promotion and rollback. + +### Blue-Green Flow + +Initial active version: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ helm upgrade --install lab14-bluegreen k8s/devops-python -n lab14 -f k8s/devops-python/values-bluegreen.yaml --timeout 10m +Release "lab14-bluegreen" does not exist. Installing it now. +NAME: lab14-bluegreen +LAST DEPLOYED: Sat Apr 25 15:45:00 2026 +NAMESPACE: lab14 +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None +``` + +Preview version: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ helm upgrade lab14-bluegreen k8s/devops-python -n lab14 -f k8s/devops-python/values-bluegreen-update.yaml --timeout 10m +Release "lab14-bluegreen" has been upgraded. Happy Helming! +NAME: lab14-bluegreen +LAST DEPLOYED: Sat Apr 25 15:46:03 2026 +NAMESPACE: lab14 +STATUS: deployed +REVISION: 3 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +The updated version was held as preview because `autoPromotionEnabled: false`. + +```text +Status: Paused +Message: BlueGreenPause +revision 2: preview +revision 1: stable, active +``` + +Before promotion, active and preview services pointed to different ReplicaSets: + +```text +active service selector: rollouts-pod-template-hash=5f9dd59db +preview service selector: rollouts-pod-template-hash=bcb66b97f +``` + +Promotion switched active traffic to the preview version. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts promote lab14-bluegreen-devops-python -n lab14 +rollout 'lab14-bluegreen-devops-python' promoted +``` + +After promotion, the active service selected the new ReplicaSet. + +```text +active service selector: rollouts-pod-template-hash=bcb66b97f +preview service selector: rollouts-pod-template-hash=bcb66b97f +``` + +Instant rollback was tested with: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts undo lab14-bluegreen-devops-python -n lab14 +rollout 'lab14-bluegreen-devops-python' undo +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts promote lab14-bluegreen-devops-python -n lab14 +rollout 'lab14-bluegreen-devops-python' promoted +``` + +After rollback promotion, both services selected the previous ReplicaSet again. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl get svc lab14-bluegreen-devops-python lab14-bluegreen-devops-python-preview -n lab14 -o wide +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR +lab14-bluegreen-devops-python NodePort 10.107.152.135 80:32090/TCP 8m29s app.kubernetes.io/instance=lab14-bluegreen,app.kubernetes.io/name=devops-python,rollouts-pod-template-hash=5f9dd59db +lab14-bluegreen-devops-python-preview NodePort 10.104.130.232 80:32091/TCP 8m29s app.kubernetes.io/instance=lab14-bluegreen,app.kubernetes.io/name=devops-python,rollouts-pod-template-hash=5f9dd59db +``` + +Current final state: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts get rollout lab14-bluegreen-devops-python -n lab14 +Name: lab14-bluegreen-devops-python +Namespace: lab14 +Status: ✔ Healthy +Strategy: BlueGreen +Images: s3rap1s/devops-info-service:v2 (stable, active) +Replicas: + Desired: 4 + Current: 4 + Updated: 4 + Ready: 4 + Available: 4 +``` + +### Dashboard Evidence + +Blue-green rollout view: + +![Blue-green rollout](argocd/screenshots/argo-rollout-bluegreen.png) + +Blue-green details after final switch: + +![Blue-green rollout details](argocd/screenshots/argo-rollout-bluegreen-final.png) + + +## 4. Automated Analysis Bonus + +### Implementation + +`k8s/devops-python/templates/analysistemplate.yaml` renders an `AnalysisTemplate` when `.Values.rollout.analysis.enabled` is true. + +The failing canary test is stored in `k8s/devops-python/values-canary-analysis-fail.yaml`. + +```yaml +rollout: + analysis: + enabled: true + interval: 10s + count: 3 + failureLimit: 1 + path: /missing + canary: + steps: + - setWeight: 20 + - analysis: + templates: + - templateName: lab14-canary-devops-python-success-rate + - setWeight: 50 + - pause: + duration: 30s + - setWeight: 100 +``` + +The final rendered analysis URL is namespace-qualified: + +```yaml +url: http://lab14-canary-devops-python.lab14.svc/missing +jsonPath: "{$.status}" +successCondition: result == "healthy" +``` + +### Auto-Rollback Test + +The failing analysis rollout was started with: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ helm upgrade lab14-canary k8s/devops-python -n lab14 -f k8s/devops-python/values-canary-analysis-fail.yaml --timeout 10m +Release "lab14-canary" has been upgraded. Happy Helming! +NAME: lab14-canary +LAST DEPLOYED: Sat Apr 25 15:55:18 2026 +NAMESPACE: lab14 +STATUS: deployed +REVISION: 7 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +The analysis run failed and caused Argo Rollouts to abort the canary automatically. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl get analysisrun -n lab14 +NAME STATUS AGE +lab14-canary-devops-python-f448b5d7-5-1 Error 3m22s +lab14-canary-devops-python-f448b5d7-7-1 Error 63s +``` + +The second analysis run used the final namespace-qualified service URL and failed because `/missing` returned 404. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl describe analysisrun lab14-canary-devops-python-f448b5d7-7-1 -n lab14 +URL: http://lab14-canary-devops-python.lab14.svc/missing +Success Condition: result == "healthy" +Message: received non 2xx response code: 404 +Phase: Error +``` + +The rollout status reported an automatic abort: + +```text +Degraded - RolloutAborted: Rollout aborted update to revision 7: +Step-based analysis phase error/failed: Metric "webcheck" assessed Error +``` + +This verifies behavior: a failed analysis step automatically aborts the canary and keeps the previous stable ReplicaSet serving traffic. + +The canary release was restored with: + +```bash +helm rollback lab14-canary 6 -n lab14 --timeout 10m +``` + +Final state after rollback: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab14 λ kubectl argo rollouts get rollout lab14-canary-devops-python -n lab14 +Name: lab14-canary-devops-python +Namespace: lab14 +Status: ✔ Healthy +Strategy: Canary + Step: 9/9 + SetWeight: 100 + ActualWeight: 100 +Replicas: + Desired: 5 + Current: 5 + Updated: 5 + Ready: 5 + Available: 5 +``` + + +## 5. Strategy Comparison + +Canary is better when a release should be exposed gradually and monitored while traffic increases. +It uses fewer extra resources than blue-green, but rollback is step-based and users may temporarily hit both versions. + +Blue-green is better when the new version must be tested in isolation before a fast switch. +Promotion and rollback are nearly instant because they switch service selectors, +but the cluster needs enough capacity to run active and preview ReplicaSets at the same time. + +Recommendation: + +- use canary for user-facing changes where gradual exposure reduces risk +- use blue-green for releases that need a full preview environment and fast rollback +- use automated analysis with canary when there is a clear health or metrics signal that can safely decide promotion or abort + + +## 6. CLI Commands Reference + +Useful commands from this lab: + +```bash +kubectl get pods -n argo-rollouts -o wide +kubectl argo rollouts version +kubectl port-forward svc/argo-rollouts-dashboard -n argo-rollouts 3101:3100 + +helm upgrade --install lab14-canary k8s/devops-python -n lab14 -f k8s/devops-python/values-canary.yaml --timeout 10m +helm upgrade lab14-canary k8s/devops-python -n lab14 -f k8s/devops-python/values-canary-update.yaml --timeout 10m +kubectl argo rollouts get rollout lab14-canary-devops-python -n lab14 +kubectl argo rollouts promote lab14-canary-devops-python -n lab14 +kubectl argo rollouts abort lab14-canary-devops-python -n lab14 + +helm upgrade --install lab14-bluegreen k8s/devops-python -n lab14 -f k8s/devops-python/values-bluegreen.yaml --timeout 10m +helm upgrade lab14-bluegreen k8s/devops-python -n lab14 -f k8s/devops-python/values-bluegreen-update.yaml --timeout 10m +kubectl argo rollouts get rollout lab14-bluegreen-devops-python -n lab14 +kubectl argo rollouts promote lab14-bluegreen-devops-python -n lab14 +kubectl argo rollouts undo lab14-bluegreen-devops-python -n lab14 + +kubectl get svc -n lab14 +kubectl get analysisrun -n lab14 +kubectl describe analysisrun -n lab14 +helm rollback -n lab14 --timeout 10m +``` diff --git a/k8s/SECRETS.md b/k8s/SECRETS.md new file mode 100644 index 0000000000..2a4e736155 --- /dev/null +++ b/k8s/SECRETS.md @@ -0,0 +1,348 @@ +# Lab 11: Kubernetes Secrets & HashiCorp Vault + +## Kubernetes Secrets + +### Create Secret + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl create secret generic app-credentials --from-literal=username=*user* --from-literal=password=*pass* +secret/app-credentials created +``` + +### View Secret + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl get secret app-credentials -o yaml +apiVersion: v1 +data: + password: c2VjcmV0MTIz + username: YWRtaW4= +kind: Secret +metadata: + creationTimestamp: "2026-04-09T08:31:08Z" + name: app-credentials + namespace: default + resourceVersion: "20349" + uid: 758e4980-2d88-4f4d-b3e8-d5d0f1bad3c5 +type: Opaque +``` + +### Decode Values + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl get secret app-credentials -o jsonpath='{.data.username}' | base64 -d +*user* + +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl get secret app-credentials -o jsonpath='{.data.password}' | base64 -d +*pass* +``` + +Kubernetes Secrets are base64-encoded, not encrypted by default. Base64 only changes representation; anyone with API access to the Secret can decode it. + +Secrets are not encrypted at rest by default unless the cluster administrator enables etcd encryption with an API server `EncryptionConfiguration`. In production this should be enabled. + + +## Helm Secret Integration + +### Chart Structure + +```text +k8s/devops-python/ +├── Chart.yaml +├── values.yaml +├── values-dev.yaml +├── values-prod.yaml +└── templates/ + ├── deployment.yaml + ├── service.yaml + ├── secrets.yaml + ├── serviceaccount.yaml + ├── pre-install-job.yaml + └── post-install-job.yaml +``` + +### Secret Consumption + +The chart now creates a Kubernetes `Secret` in `templates/secrets.yaml` and injects it into the application pod through `envFrom.secretRef` in `templates/deployment.yaml`. + +Rendered chart verification: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ helm template lab11-release k8s/devops-python -f k8s/devops-python/values-dev.yaml --set secret.username=*user* --set secret.password=*pass* +# Source: devops-python/templates/serviceaccount.yaml +kind: ServiceAccount +# Source: devops-python/templates/secrets.yaml +kind: Secret +stringData: + username: "*user*" + password: "*pass*" +# Source: devops-python/templates/service.yaml +kind: Service +# Source: devops-python/templates/deployment.yaml +kind: Deployment + serviceAccountName: lab11-release-devops-python + envFrom: + - secretRef: +# Source: devops-python/templates/post-install-job.yaml +kind: Job +# Source: devops-python/templates/pre-install-job.yaml +kind: Job +``` + +Installed release resources: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl get all -l app.kubernetes.io/instance=lab11-release +NAME READY STATUS RESTARTS AGE +pod/lab11-release-devops-python-644969578d-fnswb 2/2 Running 0 49s + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/lab11-release-devops-python NodePort 10.109.51.125 80:31192/TCP 5m34s + +NAME READY UP-TO-DATE AVAILABLE AGE +deployment.apps/lab11-release-devops-python 1/1 1 1 5m34s + +NAME DESIRED CURRENT READY AGE +replicaset.apps/lab11-release-devops-python-644969578d 1 1 1 49s +replicaset.apps/lab11-release-devops-python-79df994fc8 0 0 0 5m34s +``` + +Environment variable can be seen with this command + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ POD=$(kubectl get pods -l app.kubernetes.io/instance=lab11-release -o jsonpath='{.items[0].metadata.name}'); kubectl exec "$POD" -c app -- env +``` + +`kubectl describe pod` does not expose the secret values themselves, to see them use this command: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ POD=$(kubectl get pods -l app.kubernetes.io/instance=lab11-release -o jsonpath='{.items[0].metadata.name}'); kubectl describe pod "$POD" +``` + +## Resource Management + +### Configuration + +The deployment uses configurable requests and limits from `values.yaml`: + +```yaml +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 200m + memory: 256Mi +``` + +Development overrides in `values-dev.yaml`: + +```yaml +resources: + requests: + cpu: 50m + memory: 64Mi + limits: + cpu: 100m + memory: 128Mi +``` + +Requests define the minimum resources Kubernetes should reserve for the container. Limits define the maximum resources the container is allowed to consume. + +For this service, small dev values are enough because the app is lightweight. In production the values should be chosen from observed CPU and memory usage, then increased with some headroom for traffic spikes. + + +## Vault Integration + +### Vault Installation + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ helm repo add hashicorp https://helm.releases.hashicorp.com +"hashicorp" has been added to your repositories +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ 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 +Update Complete. ⎈Happy Helming!⎈ +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ helm search repo hashicorp/vault +NAME CHART VERSION APP VERSION DESCRIPTION +hashicorp/vault 0.32.0 1.21.2 Official HashiCorp Vault Chart +hashicorp/vault-radar-agent 0.1.0 0.42.0 Official HashiCorp Vault Radar Agent Chart +hashicorp/vault-secrets-gateway 0.0.2 0.1.0 A Helm chart for Kubernetes +hashicorp/vault-secrets-operator 1.3.0 1.3.0 Official Vault Secrets Operator Chart +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ helm install vault hashicorp/vault --set server.dev.enabled=true --set injector.enabled=true --wait +NAME: vault +LAST DEPLOYED: Thu Apr 9 11:35:19 2026 +NAMESPACE: default +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +NOTES: +Thank you for installing HashiCorp Vault! + +Now that you have deployed Vault, you should look over the docs on using +Vault with Kubernetes available here: + +https://developer.hashicorp.com/vault/docs + + +Your release is named vault. To learn more about the release, try: + + $ helm status vault + $ helm get manifest vault +``` + +Vault pods verification: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl get pods -l app.kubernetes.io/instance=vault +NAME READY STATUS RESTARTS AGE +vault-0 1/1 Running 0 2m12s +vault-agent-injector-848dd747d7-lvs5l 1/1 Running 0 2m50s +``` + +### Vault Configuration + +Vault status: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault status' +Key Value +--- ----- +Seal Type shamir +Initialized true +Sealed false +Total Shares 1 +Threshold 1 +Version 1.21.2 +Build Date 2026-01-06T08:33:05Z +Storage Type inmem +Cluster Name vault-cluster-0ea77300 +Cluster ID 027a6918-eb5c-7fe9-fd7c-9ddf393053fe +HA Enabled false +``` + +KV engine and secret creation: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault secrets enable -path=kv kv-v2' +Success! Enabled the kv-v2 secrets engine at: kv/ +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault kv put kv/myapp/config username=*user* password=*pass*' +==== Secret Path ==== +kv/data/myapp/config + +======= Metadata ======= +Key Value +--- ----- +created_time 2026-04-09T08:36:51.710336864Z +custom_metadata +deletion_time n/a +destroyed false +version 1 +``` + +Kubernetes auth configuration: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault auth enable kubernetes' +Success! Enabled kubernetes auth method at: kubernetes/ +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault write auth/kubernetes/config token_reviewer_jwt=@/var/run/secrets/kubernetes.io/serviceaccount/token kubernetes_host="https://${KUBERNETES_PORT_443_TCP_ADDR}:443" kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt' +Success! Data written to: auth/kubernetes/config +``` + +Policy and role: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault policy read devops-python-policy' +path "kv/data/myapp/config" { + capabilities = ["read"] +} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl exec vault-0 -- sh -lc 'export VAULT_ADDR=http://127.0.0.1:8200 VAULT_TOKEN=root; vault read auth/kubernetes/role/devops-python-role' +Key Value +--- ----- +alias_name_source serviceaccount_uid +bound_service_account_names [lab11-release-devops-python] +bound_service_account_namespace_selector n/a +bound_service_account_namespaces [default] +policies [devops-python-policy] +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 [devops-python-policy] +token_ttl 24h +token_type default +ttl 24h +``` + +### Injection Verification + +The deployment was upgraded with Vault annotations so the injector adds a sidecar and mounts rendered secrets into `/vault/secrets`. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ kubectl get pods -l app.kubernetes.io/instance=lab11-release -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +lab11-release-devops-python-644969578d-fnswb 2/2 Running 0 23s 10.244.0.89 minikube +lab11-release-devops-python-79df994fc8-hdw8t 1/1 Terminating 0 5m8s 10.244.0.84 minikube +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ POD=$(kubectl get pods -l app.kubernetes.io/instance=lab11-release -o jsonpath='{.items[0].metadata.name}'); kubectl describe pod "$POD" | sed -n '/Annotations:/,/Containers:/p' +Annotations: vault.hashicorp.com/agent-inject: true + vault.hashicorp.com/agent-inject-secret-config.txt: kv/data/myapp/config + vault.hashicorp.com/agent-inject-status: injected + vault.hashicorp.com/role: devops-python-role +Status: Running +IP: 10.244.0.89 +IPs: + IP: 10.244.0.89 +Controlled By: ReplicaSet/lab11-release-devops-python-644969578d +Init Containers: +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab11 λ POD=$(kubectl get pods -l app.kubernetes.io/instance=lab11-release -o jsonpath='{.items[0].metadata.name}'); kubectl exec "$POD" -c app -- sh -lc 'find /vault -maxdepth 2 -type f | sort' +/vault/secrets/config.txt +``` + +This uses the sidecar injection pattern: Vault Agent is injected into the pod, authenticates to Vault using the pod's Kubernetes service account, reads the permitted secret path, and writes the secret to a shared volume that the application container can read as a file. + + +## Security Analysis + +### Kubernetes Secrets vs Vault +- Kubernetes Secrets are simple, native, and enough for small internal workloads that only need basic secret distribution inside the cluster. +- Vault provides stronger secret management with dedicated access policies, secret versioning, dynamic credentials, and a cleaner separation between application deployment and secret storage. +- Kubernetes Secrets are stored in etcd and depend heavily on cluster hardening. +- Vault keeps secret access behind explicit auth methods and policies, which scales better for production systems. + +### When To Use Each +- Use Kubernetes Secrets for simple cluster-local configuration when the security requirements are moderate and operational simplicity matters. +- Use Vault when you need stronger access control, rotation, dynamic secrets, or centralized secret management across multiple applications and platforms. + +### Production Recommendations +- Enable etcd encryption at rest for Kubernetes Secrets. +- Restrict secret access with RBAC and least privilege. +- Do not store real credentials in Git or Helm values files. +- Use Vault or another external secret manager for production credentials. +- Prefer short-lived or dynamic credentials where possible. diff --git a/k8s/STATEFULSET.md b/k8s/STATEFULSET.md new file mode 100644 index 0000000000..950415155c --- /dev/null +++ b/k8s/STATEFULSET.md @@ -0,0 +1,389 @@ +# Lab 15: StatefulSets & Persistent Storage + +## 1. StatefulSet Overview + +StatefulSet is used when each replica needs a stable identity and its own persistent storage. In this lab the Python application keeps a visits counter in `/data/visits`, so StatefulSet is a better fit than Deployment when each replica must keep a separate counter. + +Main differences from Deployment: + +- Deployment creates interchangeable pods with random suffixes +- StatefulSet creates ordered pods: `app-0`, `app-1`, `app-2` +- Deployment usually shares one PVC or uses stateless pods +- StatefulSet creates one PVC per pod through `volumeClaimTemplates` +- Deployment scales and replaces pods in any order +- StatefulSet uses ordered creation, update, and termination by default +- StatefulSet pods get stable DNS names through a headless service + +Examples of workloads that need StatefulSet behavior: + +- PostgreSQL, MySQL, MongoDB, Kafka, Elasticsearch + + +## 2. Implementation + +The Helm chart keeps the Lab 14 `rollout.yaml` for progressive delivery and adds a separate StatefulSet mode controlled by values. + +New templates: + +- `k8s/devops-python/templates/statefulset.yaml` +- `k8s/devops-python/templates/headless-service.yaml` + +New values files: + +- `k8s/devops-python/values-statefulset.yaml` +- `k8s/devops-python/values-statefulset-partition.yaml` +- `k8s/devops-python/values-statefulset-ondelete.yaml` + +StatefulSet mode is enabled with: + +```yaml +workload: + type: statefulset +``` + +The StatefulSet points to the headless service: + +```yaml +spec: + serviceName: lab15-stateful-devops-python-headless + replicas: 3 + podManagementPolicy: OrderedReady +``` + +Each pod gets its own PVC from `volumeClaimTemplates`: + +```yaml +volumeClaimTemplates: + - metadata: + name: data-volume + spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 100Mi +``` + + +## 3. Deployment Verification + +The namespace and Helm release were created: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl create namespace lab15 +namespace/lab15 created +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ helm upgrade --install lab15-stateful k8s/devops-python -n lab15 -f k8s/devops-python/values-statefulset.yaml --timeout 10m +Release "lab15-stateful" does not exist. Installing it now. +NAME: lab15-stateful +LAST DEPLOYED: Sat Apr 25 16:32:46 2026 +NAMESPACE: lab15 +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None +``` + +After switching the release to the local `lab15` image, the StatefulSet rolled out successfully: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ helm upgrade lab15-stateful k8s/devops-python -n lab15 -f k8s/devops-python/values-statefulset.yaml --timeout 10m +Release "lab15-stateful" has been upgraded. Happy Helming! +NAME: lab15-stateful +LAST DEPLOYED: Sat Apr 25 16:45:41 2026 +NAMESPACE: lab15 +STATUS: deployed +REVISION: 2 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl rollout status statefulset/lab15-stateful-devops-python -n lab15 --timeout=300s +statefulset rolling update complete 3 pods at revision lab15-stateful-devops-python-68f678c6cd... +``` + +Resource verification: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl get po,sts,svc,pvc -n lab15 -l app.kubernetes.io/instance=lab15-stateful +NAME READY STATUS RESTARTS AGE +pod/lab15-stateful-devops-python-0 1/1 Running 0 5m56s +pod/lab15-stateful-devops-python-1 1/1 Running 0 39s +pod/lab15-stateful-devops-python-2 1/1 Running 0 80s + +NAME READY AGE +statefulset.apps/lab15-stateful-devops-python 3/3 22m + +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +service/lab15-stateful-devops-python NodePort 10.105.188.156 80:32150/TCP 22m +service/lab15-stateful-devops-python-headless ClusterIP None 80/TCP 22m + +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE +persistentvolumeclaim/data-volume-lab15-stateful-devops-python-0 Bound pvc-6b91f75d-e02c-49ae-b077-7b322561a154 100Mi RWO standard 22m +persistentvolumeclaim/data-volume-lab15-stateful-devops-python-1 Bound pvc-f2a1ddc3-2b1d-412e-b7de-8e7a1a391088 100Mi RWO standard 22m +persistentvolumeclaim/data-volume-lab15-stateful-devops-python-2 Bound pvc-7d027d30-93b2-4241-b23a-850805afe452 100Mi RWO standard 21m +``` + +This confirms: + +- stable pod names with ordinal suffixes +- one StatefulSet with 3 ready replicas +- external NodePort service for normal access +- headless service with `CLUSTER-IP: None` +- one PVC per pod + + +## 4. Network Identity + +The headless service is named `lab15-stateful-devops-python-headless`. + +DNS naming pattern: + +```text +...svc.cluster.local +``` + +Examples: + +```text +lab15-stateful-devops-python-0.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +lab15-stateful-devops-python-1.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +lab15-stateful-devops-python-2.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +``` + +DNS resolution from pod `0` to pod `1`: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-0 -n lab15 -- getent hosts lab15-stateful-devops-python-1.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +Defaulted container "app" out of: app, volume-permissions (init) +10.244.1.43 lab15-stateful-devops-python-1.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +``` + +DNS resolution from pod `0` to pod `2`: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-0 -n lab15 -- getent hosts lab15-stateful-devops-python-2.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +Defaulted container "app" out of: app, volume-permissions (init) +10.244.1.44 lab15-stateful-devops-python-2.lab15-stateful-devops-python-headless.lab15.svc.cluster.local +``` + + +## 5. Per-Pod Storage Evidence + +Each pod was accessed through a direct pod port-forward: + +```bash +kubectl port-forward pod/lab15-stateful-devops-python-0 -n lab15 15250:5000 +kubectl port-forward pod/lab15-stateful-devops-python-1 -n lab15 15251:5000 +kubectl port-forward pod/lab15-stateful-devops-python-2 -n lab15 15252:5000 +``` + +The root endpoint was called a different number of times per pod: + +- pod `0`: 2 requests +- pod `1`: 1 request +- pod `2`: 3 requests + +The `/visits` endpoint returned different values for each pod: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ curl -s http://127.0.0.1:15250/visits +{"file":"/data/visits","visits":2} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ curl -s http://127.0.0.1:15251/visits +{"file":"/data/visits","visits":1} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ curl -s http://127.0.0.1:15252/visits +{"file":"/data/visits","visits":3} +``` + +The files inside the pods matched the endpoint output: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-0 -n lab15 -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +2 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-1 -n lab15 -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +1 +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-2 -n lab15 -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +3 +``` + +This proves that each pod has isolated persistent storage. + + +## 6. Persistence Test + +Before deletion, pod `0` had this value: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-0 -n lab15 -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +2 +``` + +The pod was deleted directly: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl delete pod lab15-stateful-devops-python-0 -n lab15 +pod "lab15-stateful-devops-python-0" deleted from lab15 namespace +``` + +StatefulSet recreated the same ordinal: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl wait pod/lab15-stateful-devops-python-0 -n lab15 --for=condition=Ready --timeout=180s +pod/lab15-stateful-devops-python-0 condition met +``` + +The pod got a new IP but kept the same name and PVC: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl get pod lab15-stateful-devops-python-0 -n lab15 -o wide +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +lab15-stateful-devops-python-0 1/1 Running 0 22s 10.244.1.48 minikube +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl get pvc data-volume-lab15-stateful-devops-python-0 -n lab15 +NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE +data-volume-lab15-stateful-devops-python-0 Bound pvc-6b91f75d-e02c-49ae-b077-7b322561a154 100Mi RWO standard 16m +``` + +The visit count was preserved: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-0 -n lab15 -- cat /data/visits +Defaulted container "app" out of: app, volume-permissions (init) +2 +``` + + +## 7. Update Strategy Bonus + +### Partitioned Rolling Update + +The partitioned values file uses `partition: 2`. + +```yaml +statefulset: + updateStrategy: + type: RollingUpdate + partition: 2 +``` + +The release was updated: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ helm upgrade lab15-stateful k8s/devops-python -n lab15 -f k8s/devops-python/values-statefulset-partition.yaml --timeout 10m +Release "lab15-stateful" has been upgraded. Happy Helming! +NAME: lab15-stateful +LAST DEPLOYED: Sat Apr 25 16:49:38 2026 +NAMESPACE: lab15 +STATUS: deployed +REVISION: 3 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +Only one pod was updated because only ordinal `2` is greater than or equal to the partition. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl rollout status statefulset/lab15-stateful-devops-python -n lab15 --timeout=180s +partitioned roll out complete: 1 new pods have been updated... +``` + +Replica revisions after the partitioned update: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl get pods -n lab15 -l app.kubernetes.io/instance=lab15-stateful -o 'custom-columns=NAME:.metadata.name,REVISION:.metadata.labels.controller-revision-hash,READY:.status.containerStatuses[0].ready' +NAME REVISION READY +lab15-stateful-devops-python-0 lab15-stateful-devops-python-68f678c6cd true +lab15-stateful-devops-python-1 lab15-stateful-devops-python-68f678c6cd true +lab15-stateful-devops-python-2 lab15-stateful-devops-python-58ccd655bb true +``` + +Environment values confirmed the same result: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-0 -n lab15 -- printenv APP_ENV +Defaulted container "app" out of: app, volume-permissions (init) +statefulset +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-2 -n lab15 -- printenv APP_ENV +Defaulted container "app" out of: app, volume-permissions (init) +statefulset-partition +``` + +### OnDelete Strategy + +The OnDelete values file uses: + +```yaml +statefulset: + updateStrategy: + type: OnDelete +``` + +The release was updated: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ helm upgrade lab15-stateful k8s/devops-python -n lab15 -f k8s/devops-python/values-statefulset-ondelete.yaml --timeout 10m +Release "lab15-stateful" has been upgraded. Happy Helming! +NAME: lab15-stateful +LAST DEPLOYED: Sat Apr 25 16:50:56 2026 +NAMESPACE: lab15 +STATUS: deployed +REVISION: 4 +DESCRIPTION: Upgrade complete +TEST SUITE: None +``` + +The StatefulSet accepted the OnDelete strategy: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl get statefulset lab15-stateful-devops-python -n lab15 -o jsonpath='{.spec.updateStrategy.type}{"\n"}' +OnDelete +``` + +Pods were not recreated automatically after the Helm upgrade: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl get pods -n lab15 -l app.kubernetes.io/instance=lab15-stateful -o 'custom-columns=NAME:.metadata.name,REVISION:.metadata.labels.controller-revision-hash,READY:.status.containerStatuses[0].ready' +NAME REVISION READY +lab15-stateful-devops-python-0 lab15-stateful-devops-python-68f678c6cd true +lab15-stateful-devops-python-1 lab15-stateful-devops-python-68f678c6cd true +lab15-stateful-devops-python-2 lab15-stateful-devops-python-58ccd655bb true +``` + +After manually deleting pod `1`, only that pod moved to the OnDelete revision: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl delete pod lab15-stateful-devops-python-1 -n lab15 +pod "lab15-stateful-devops-python-1" deleted from lab15 namespace +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab15 λ kubectl exec lab15-stateful-devops-python-1 -n lab15 -- printenv APP_ENV +Defaulted container "app" out of: app, volume-permissions (init) +statefulset-ondelete +``` + +OnDelete is useful when an operator wants exact manual control over which stateful replicas restart and when. This is common for databases or clustered systems where each member should be drained, checked, or promoted manually. diff --git a/k8s/argocd/application-dev.yaml b/k8s/argocd/application-dev.yaml new file mode 100644 index 0000000000..aec73be82e --- /dev/null +++ b/k8s/argocd/application-dev.yaml @@ -0,0 +1,24 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app-dev + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/s3rap1s/DevOps-Core-Course.git + targetRevision: lab13 + path: k8s/devops-python + helm: + releaseName: python-app-dev + 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..d6cbb62a41 --- /dev/null +++ b/k8s/argocd/application-prod.yaml @@ -0,0 +1,21 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app-prod + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/s3rap1s/DevOps-Core-Course.git + targetRevision: lab13 + path: k8s/devops-python + helm: + releaseName: python-app-prod + 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..d49316bda9 --- /dev/null +++ b/k8s/argocd/application.yaml @@ -0,0 +1,21 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: python-app + namespace: argocd +spec: + project: default + source: + repoURL: https://github.com/s3rap1s/DevOps-Core-Course.git + targetRevision: lab13 + path: k8s/devops-python + helm: + releaseName: python-app + valueFiles: + - values.yaml + destination: + server: https://kubernetes.default.svc + namespace: default + syncPolicy: + syncOptions: + - CreateNamespace=true diff --git a/k8s/argocd/applicationset.yaml b/k8s/argocd/applicationset.yaml new file mode 100644 index 0000000000..1d08cf8401 --- /dev/null +++ b/k8s/argocd/applicationset.yaml @@ -0,0 +1,46 @@ +apiVersion: argoproj.io/v1alpha1 +kind: ApplicationSet +metadata: + name: python-app-set + namespace: argocd +spec: + goTemplate: true + goTemplateOptions: + - missingkey=error + generators: + - list: + elements: + - env: dev + namespace: dev + valuesFile: values-dev.yaml + autoSync: "true" + - env: prod + namespace: prod + valuesFile: values-prod.yaml + autoSync: "false" + template: + metadata: + name: 'python-app-{{ .env }}' + spec: + project: default + source: + repoURL: https://github.com/s3rap1s/DevOps-Core-Course.git + targetRevision: lab13 + path: k8s/devops-python + helm: + releaseName: 'python-app-{{ .env }}' + valueFiles: + - '{{ .valuesFile }}' + destination: + server: https://kubernetes.default.svc + namespace: '{{ .namespace }}' + templatePatch: | + spec: + syncPolicy: + {{- if eq .autoSync "true" }} + automated: + prune: true + selfHeal: true + {{- end }} + syncOptions: + - CreateNamespace=true diff --git a/k8s/argocd/screenshots/argo-rollout-bluegreen-final.png b/k8s/argocd/screenshots/argo-rollout-bluegreen-final.png new file mode 100644 index 0000000000..2e6f9ba3be Binary files /dev/null and b/k8s/argocd/screenshots/argo-rollout-bluegreen-final.png differ diff --git a/k8s/argocd/screenshots/argo-rollout-bluegreen.png b/k8s/argocd/screenshots/argo-rollout-bluegreen.png new file mode 100644 index 0000000000..be13539f32 Binary files /dev/null and b/k8s/argocd/screenshots/argo-rollout-bluegreen.png differ diff --git a/k8s/argocd/screenshots/argo-rollout-details-final.png b/k8s/argocd/screenshots/argo-rollout-details-final.png new file mode 100644 index 0000000000..3cb922a060 Binary files /dev/null and b/k8s/argocd/screenshots/argo-rollout-details-final.png differ diff --git a/k8s/argocd/screenshots/argo-rollout-details.png b/k8s/argocd/screenshots/argo-rollout-details.png new file mode 100644 index 0000000000..0286eb4f1c Binary files /dev/null and b/k8s/argocd/screenshots/argo-rollout-details.png differ diff --git a/k8s/argocd/screenshots/argo-rollout-main.png b/k8s/argocd/screenshots/argo-rollout-main.png new file mode 100644 index 0000000000..28f7df6057 Binary files /dev/null and b/k8s/argocd/screenshots/argo-rollout-main.png differ diff --git a/k8s/argocd/screenshots/argocd-applications-list.png b/k8s/argocd/screenshots/argocd-applications-list.png new file mode 100644 index 0000000000..554d197c89 Binary files /dev/null and b/k8s/argocd/screenshots/argocd-applications-list.png differ diff --git a/k8s/argocd/screenshots/argocd-dev-details.png b/k8s/argocd/screenshots/argocd-dev-details.png new file mode 100644 index 0000000000..3ad1bc1694 Binary files /dev/null and b/k8s/argocd/screenshots/argocd-dev-details.png differ diff --git a/k8s/argocd/screenshots/argocd-prod-details.png b/k8s/argocd/screenshots/argocd-prod-details.png new file mode 100644 index 0000000000..c16979fea8 Binary files /dev/null and b/k8s/argocd/screenshots/argocd-prod-details.png differ diff --git a/k8s/common-lib/Chart.yaml b/k8s/common-lib/Chart.yaml new file mode 100644 index 0000000000..0515f07019 --- /dev/null +++ b/k8s/common-lib/Chart.yaml @@ -0,0 +1,5 @@ +apiVersion: v2 +name: common-lib +description: Shared Helm templates for DevOps course applications +type: library +version: 0.1.0 diff --git a/k8s/common-lib/templates/_helpers.tpl b/k8s/common-lib/templates/_helpers.tpl new file mode 100644 index 0000000000..570ee5dedf --- /dev/null +++ b/k8s/common-lib/templates/_helpers.tpl @@ -0,0 +1,27 @@ +{{- define "common.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- define "common.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name (include "common.name" .) | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} + +{{- define "common.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- define "common.selectorLabels" -}} +app.kubernetes.io/name: {{ include "common.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end -}} + +{{- define "common.labels" -}} +helm.sh/chart: {{ include "common.chart" . }} +{{ include "common.selectorLabels" . }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} diff --git a/k8s/deployment.yml b/k8s/deployment.yml new file mode 100644 index 0000000000..5f91210970 --- /dev/null +++ b/k8s/deployment.yml @@ -0,0 +1,50 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: devops-python + labels: + app: devops-python +spec: + replicas: 5 + selector: + matchLabels: + app: devops-python + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + template: + metadata: + labels: + app: devops-python + spec: + containers: + - name: app + image: s3rap1s/devops-info-service:v2 + ports: + - containerPort: 5000 + env: + - name: PORT + value: "5000" + - name: HOST + value: "0.0.0.0" + resources: + requests: + memory: "128Mi" + cpu: "100m" + limits: + memory: "256Mi" + cpu: "200m" + livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 15 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 5 \ No newline at end of file diff --git a/k8s/devops-go/.helmignore b/k8s/devops-go/.helmignore new file mode 100644 index 0000000000..97e7f7b037 --- /dev/null +++ b/k8s/devops-go/.helmignore @@ -0,0 +1,7 @@ +# Patterns to ignore when building packages. +.DS_Store +.git/ +.gitignore +*.swp +*.bak +*.tmp diff --git a/k8s/devops-go/Chart.yaml b/k8s/devops-go/Chart.yaml new file mode 100644 index 0000000000..a95e05c21f --- /dev/null +++ b/k8s/devops-go/Chart.yaml @@ -0,0 +1,18 @@ +apiVersion: v2 +name: devops-go +description: Helm chart for the DevOps Go information service +type: application +version: 0.1.0 +appVersion: "1.0.0" +keywords: + - devops + - go + - kubernetes +maintainers: + - name: Amirkhan Kurbanov +sources: + - https://github.com/s3rap1s/DevOps-Core-Course +dependencies: + - name: common-lib + version: 0.1.0 + repository: "file://../common-lib" diff --git a/k8s/devops-go/templates/deployment.yaml b/k8s/devops-go/templates/deployment.yaml new file mode 100644 index 0000000000..fdf2136cc1 --- /dev/null +++ b/k8s/devops-go/templates/deployment.yaml @@ -0,0 +1,39 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "common.fullname" . }} + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "common.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "common.selectorLabels" . | nindent 8 }} + spec: + containers: + - name: app + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.container.port }} + protocol: TCP + env: + {{- range .Values.env }} + - name: {{ .name }} + value: {{ .value | quote }} + {{- end }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.livenessProbe }} + livenessProbe: + {{- toYaml . | nindent 12 }} + {{- end }} + {{- with .Values.readinessProbe }} + readinessProbe: + {{- toYaml . | nindent 12 }} + {{- end }} diff --git a/k8s/devops-go/templates/service.yaml b/k8s/devops-go/templates/service.yaml new file mode 100644 index 0000000000..3cb0eb0414 --- /dev/null +++ b/k8s/devops-go/templates/service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "common.fullname" . }} + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + selector: + {{- include "common.selectorLabels" . | nindent 4 }} + ports: + - name: http + protocol: TCP + port: {{ .Values.service.port }} + targetPort: {{ .Values.service.targetPort }} diff --git a/k8s/devops-go/values.yaml b/k8s/devops-go/values.yaml new file mode 100644 index 0000000000..2cd11227e0 --- /dev/null +++ b/k8s/devops-go/values.yaml @@ -0,0 +1,45 @@ +nameOverride: "" +fullnameOverride: "" + +replicaCount: 2 + +image: + repository: s3rap1s/devops-info-service-go + tag: "latest" + pullPolicy: IfNotPresent + +service: + type: ClusterIP + port: 80 + targetPort: 5000 + +container: + port: 5000 + +env: + - name: PORT + value: "5000" + - name: HOST + value: "0.0.0.0" + +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 200m + memory: 256Mi + +livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 10 + periodSeconds: 10 + +readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 5 diff --git a/k8s/devops-python/.helmignore b/k8s/devops-python/.helmignore new file mode 100644 index 0000000000..0e8a0eb36f --- /dev/null +++ b/k8s/devops-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/devops-python/Chart.yaml b/k8s/devops-python/Chart.yaml new file mode 100644 index 0000000000..e6d6f5cc31 --- /dev/null +++ b/k8s/devops-python/Chart.yaml @@ -0,0 +1,19 @@ +apiVersion: v2 +name: devops-python +description: Helm chart for the DevOps Python information service +type: application +version: 0.1.0 +appVersion: "2.0.0" +keywords: + - devops + - python + - flask + - kubernetes +maintainers: + - name: Amirkhan Kurbanov +sources: + - https://github.com/s3rap1s/DevOps-Core-Course +dependencies: + - name: common-lib + version: 0.1.0 + repository: "file://../common-lib" diff --git a/k8s/devops-python/files/config.json b/k8s/devops-python/files/config.json new file mode 100644 index 0000000000..74f7da8f35 --- /dev/null +++ b/k8s/devops-python/files/config.json @@ -0,0 +1,8 @@ +{ + "application_name": "{{ .Values.configFile.applicationName }}", + "environment": "{{ .Values.configFile.environment }}", + "settings": { + "featureGreeting": {{ .Values.configFile.settings.featureGreeting }}, + "maxVisitsDisplay": {{ .Values.configFile.settings.maxVisitsDisplay }} + } +} diff --git a/k8s/devops-python/templates/analysistemplate.yaml b/k8s/devops-python/templates/analysistemplate.yaml new file mode 100644 index 0000000000..53e0d64c2a --- /dev/null +++ b/k8s/devops-python/templates/analysistemplate.yaml @@ -0,0 +1,19 @@ +{{- if and .Values.rollout.analysis.enabled (ne .Values.workload.type "statefulset") }} +apiVersion: argoproj.io/v1alpha1 +kind: AnalysisTemplate +metadata: + name: {{ include "common.fullname" . }}-success-rate + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + metrics: + - name: webcheck + interval: {{ .Values.rollout.analysis.interval }} + count: {{ .Values.rollout.analysis.count }} + failureLimit: {{ .Values.rollout.analysis.failureLimit }} + successCondition: result == "healthy" + provider: + web: + url: http://{{ include "common.fullname" . }}.{{ .Release.Namespace }}.svc{{ .Values.rollout.analysis.path }} + jsonPath: "{$.status}" +{{- end }} diff --git a/k8s/devops-python/templates/configmap.yaml b/k8s/devops-python/templates/configmap.yaml new file mode 100644 index 0000000000..dffca09640 --- /dev/null +++ b/k8s/devops-python/templates/configmap.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "common.fullname" . }}-config + labels: + {{- include "common.labels" . | nindent 4 }} +data: + config.json: |- +{{ tpl (.Files.Get "files/config.json") . | indent 4 }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "common.fullname" . }}-env + labels: + {{- include "common.labels" . | nindent 4 }} +data: +{{- range $key, $value := .Values.configEnv }} + {{ $key }}: {{ $value | quote }} +{{- end }} diff --git a/k8s/devops-python/templates/headless-service.yaml b/k8s/devops-python/templates/headless-service.yaml new file mode 100644 index 0000000000..9a896ca201 --- /dev/null +++ b/k8s/devops-python/templates/headless-service.yaml @@ -0,0 +1,17 @@ +{{- if eq .Values.workload.type "statefulset" }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "common.fullname" . }}-headless + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + clusterIP: None + selector: + {{- include "common.selectorLabels" . | nindent 4 }} + ports: + - name: http + protocol: TCP + port: {{ .Values.service.port }} + targetPort: {{ .Values.service.targetPort }} +{{- end }} diff --git a/k8s/devops-python/templates/post-install-job.yaml b/k8s/devops-python/templates/post-install-job.yaml new file mode 100644 index 0000000000..0474e78cd0 --- /dev/null +++ b/k8s/devops-python/templates/post-install-job.yaml @@ -0,0 +1,30 @@ +{{- if .Values.hooks.postInstall.enabled }} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ include "common.fullname" . }}-post-install + labels: + {{- include "common.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": post-install + "helm.sh/hook-weight": "{{ .Values.hooks.postInstall.weight }}" + "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded +spec: + backoffLimit: 0 + template: + metadata: + labels: + {{- include "common.selectorLabels" . | nindent 8 }} + spec: + restartPolicy: Never + containers: + - name: post-install-smoke-test + image: {{ .Values.hooks.image }} + command: + - sh + - -c + - | + wget -qO- http://{{ include "common.fullname" . }}:{{ .Values.service.port }}/health && \ + echo "Post-install smoke test passed" && \ + sleep 10 +{{- end }} diff --git a/k8s/devops-python/templates/pre-install-job.yaml b/k8s/devops-python/templates/pre-install-job.yaml new file mode 100644 index 0000000000..36e7640e68 --- /dev/null +++ b/k8s/devops-python/templates/pre-install-job.yaml @@ -0,0 +1,30 @@ +{{- if .Values.hooks.preInstall.enabled }} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ include "common.fullname" . }}-pre-install + labels: + {{- include "common.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": pre-install + "helm.sh/hook-weight": "{{ .Values.hooks.preInstall.weight }}" + "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded +spec: + backoffLimit: 0 + template: + metadata: + labels: + {{- include "common.selectorLabels" . | nindent 8 }} + spec: + restartPolicy: Never + containers: + - name: pre-install-check + image: {{ .Values.hooks.image }} + command: + - sh + - -c + - | + test -n "{{ .Values.image.repository }}" && \ + echo "Pre-install validation passed for {{ .Values.image.repository }}:{{ .Values.image.tag }}" && \ + sleep 10 +{{- end }} diff --git a/k8s/devops-python/templates/pvc.yaml b/k8s/devops-python/templates/pvc.yaml new file mode 100644 index 0000000000..0c63e5501f --- /dev/null +++ b/k8s/devops-python/templates/pvc.yaml @@ -0,0 +1,17 @@ +{{- if and .Values.persistence.enabled (ne .Values.workload.type "statefulset") }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "common.fullname" . }}-data + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + accessModes: + - {{ .Values.persistence.accessMode }} + resources: + requests: + storage: {{ .Values.persistence.size }} + {{- if .Values.persistence.storageClass }} + storageClassName: {{ .Values.persistence.storageClass | quote }} + {{- end }} +{{- end }} diff --git a/k8s/devops-python/templates/rollout.yaml b/k8s/devops-python/templates/rollout.yaml new file mode 100644 index 0000000000..bc70af5125 --- /dev/null +++ b/k8s/devops-python/templates/rollout.yaml @@ -0,0 +1,150 @@ +{{- if ne .Values.workload.type "statefulset" }} +apiVersion: argoproj.io/v1alpha1 +kind: Rollout +metadata: + name: {{ include "common.fullname" . }} + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + revisionHistoryLimit: {{ .Values.rollout.revisionHistoryLimit }} + selector: + matchLabels: + {{- include "common.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "common.selectorLabels" . | nindent 8 }} + annotations: + checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} + {{- if .Values.vault.enabled }} + vault.hashicorp.com/agent-inject: "true" + vault.hashicorp.com/role: {{ .Values.vault.role | quote }} + vault.hashicorp.com/agent-inject-secret-config.txt: {{ .Values.vault.secretPath | quote }} + {{- end }} + spec: + serviceAccountName: {{ default (include "common.fullname" .) .Values.serviceAccount.name }} + volumes: + - name: config-volume + configMap: + name: {{ include "common.fullname" . }}-config + {{- if .Values.initContainers.enabled }} + - name: init-workdir + emptyDir: {} + {{- end }} + {{- if .Values.persistence.enabled }} + - name: data-volume + persistentVolumeClaim: + claimName: {{ include "common.fullname" . }}-data + {{- end }} + {{- if .Values.persistence.enabled }} + initContainers: + - name: volume-permissions + image: busybox:1.36.1 + command: + - sh + - -c + - mkdir -p /data && chown -R 999:999 /data + volumeMounts: + - name: data-volume + mountPath: /data + {{- if .Values.initContainers.waitForService.enabled }} + - name: wait-for-service + image: {{ .Values.initContainers.waitForService.image }} + command: + - sh + - -c + - until nslookup {{ .Values.initContainers.waitForService.host }}; do echo waiting for {{ .Values.initContainers.waitForService.host }}; sleep 2; done + {{- end }} + {{- if .Values.initContainers.download.enabled }} + - name: init-download + image: {{ .Values.initContainers.download.image }} + command: + - sh + - -c + - wget -O {{ .Values.initContainers.sharedMountPath }}/{{ .Values.initContainers.download.outputFile }} {{ .Values.initContainers.download.url }} + volumeMounts: + - name: init-workdir + mountPath: {{ .Values.initContainers.sharedMountPath }} + {{- end }} + {{- else if .Values.initContainers.enabled }} + initContainers: + {{- if .Values.initContainers.waitForService.enabled }} + - name: wait-for-service + image: {{ .Values.initContainers.waitForService.image }} + command: + - sh + - -c + - until nslookup {{ .Values.initContainers.waitForService.host }}; do echo waiting for {{ .Values.initContainers.waitForService.host }}; sleep 2; done + {{- end }} + {{- if .Values.initContainers.download.enabled }} + - name: init-download + image: {{ .Values.initContainers.download.image }} + command: + - sh + - -c + - wget -O {{ .Values.initContainers.sharedMountPath }}/{{ .Values.initContainers.download.outputFile }} {{ .Values.initContainers.download.url }} + volumeMounts: + - name: init-workdir + mountPath: {{ .Values.initContainers.sharedMountPath }} + {{- end }} + {{- end }} + containers: + - name: app + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.container.port }} + protocol: TCP + volumeMounts: + - name: config-volume + mountPath: /config + readOnly: true + {{- if .Values.persistence.enabled }} + - name: data-volume + mountPath: /data + {{- end }} + {{- if .Values.initContainers.enabled }} + - name: init-workdir + mountPath: {{ .Values.initContainers.sharedMountPath }} + {{- end }} + envFrom: + - configMapRef: + name: {{ include "common.fullname" . }}-env + - secretRef: + name: {{ include "common.fullname" . }}-secret + env: + {{- range .Values.env }} + - name: {{ .name }} + value: {{ .value | quote }} + {{- end }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.livenessProbe }} + livenessProbe: + {{- toYaml . | nindent 12 }} + {{- end }} + {{- with .Values.readinessProbe }} + readinessProbe: + {{- toYaml . | nindent 12 }} + {{- end }} + strategy: + {{- if eq .Values.rollout.strategy "blueGreen" }} + blueGreen: + activeService: {{ include "common.fullname" . }} + previewService: {{ include "common.fullname" . }}-preview + autoPromotionEnabled: {{ .Values.rollout.blueGreen.autoPromotionEnabled }} + {{- if .Values.rollout.blueGreen.autoPromotionSeconds }} + autoPromotionSeconds: {{ .Values.rollout.blueGreen.autoPromotionSeconds }} + {{- end }} + scaleDownDelaySeconds: {{ .Values.rollout.blueGreen.scaleDownDelaySeconds }} + previewReplicaCount: {{ .Values.rollout.blueGreen.previewReplicaCount }} + {{- else }} + canary: + maxSurge: {{ .Values.rollout.canary.maxSurge | quote }} + maxUnavailable: {{ .Values.rollout.canary.maxUnavailable }} + steps: + {{- toYaml .Values.rollout.canary.steps | nindent 8 }} + {{- end }} +{{- end }} diff --git a/k8s/devops-python/templates/secrets.yaml b/k8s/devops-python/templates/secrets.yaml new file mode 100644 index 0000000000..ed4d03fddc --- /dev/null +++ b/k8s/devops-python/templates/secrets.yaml @@ -0,0 +1,12 @@ +{{- if .Values.secret.create }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "common.fullname" . }}-secret + labels: + {{- include "common.labels" . | nindent 4 }} +type: Opaque +stringData: + username: {{ .Values.secret.username | quote }} + password: {{ .Values.secret.password | quote }} +{{- end }} diff --git a/k8s/devops-python/templates/service-preview.yaml b/k8s/devops-python/templates/service-preview.yaml new file mode 100644 index 0000000000..9595d28b7c --- /dev/null +++ b/k8s/devops-python/templates/service-preview.yaml @@ -0,0 +1,18 @@ +{{- if and (eq .Values.rollout.strategy "blueGreen") (ne .Values.workload.type "statefulset") }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "common.fullname" . }}-preview + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + type: {{ .Values.rollout.blueGreen.previewService.type }} + ports: + - name: http + protocol: TCP + port: {{ .Values.rollout.blueGreen.previewService.port }} + targetPort: {{ .Values.rollout.blueGreen.previewService.targetPort }} + {{- if and (eq .Values.rollout.blueGreen.previewService.type "NodePort") .Values.rollout.blueGreen.previewService.nodePort }} + nodePort: {{ .Values.rollout.blueGreen.previewService.nodePort }} + {{- end }} +{{- end }} diff --git a/k8s/devops-python/templates/service.yaml b/k8s/devops-python/templates/service.yaml new file mode 100644 index 0000000000..8a94fdf1bb --- /dev/null +++ b/k8s/devops-python/templates/service.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "common.fullname" . }} + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + {{- if ne .Values.rollout.strategy "blueGreen" }} + selector: + {{- include "common.selectorLabels" . | nindent 4 }} + {{- end }} + ports: + - name: http + protocol: TCP + port: {{ .Values.service.port }} + targetPort: {{ .Values.service.targetPort }} + {{- if and (eq .Values.service.type "NodePort") .Values.service.nodePort }} + nodePort: {{ .Values.service.nodePort }} + {{- end }} diff --git a/k8s/devops-python/templates/serviceaccount.yaml b/k8s/devops-python/templates/serviceaccount.yaml new file mode 100644 index 0000000000..8f54862f87 --- /dev/null +++ b/k8s/devops-python/templates/serviceaccount.yaml @@ -0,0 +1,8 @@ +{{- if .Values.serviceAccount.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ default (include "common.fullname" .) .Values.serviceAccount.name }} + labels: + {{- include "common.labels" . | nindent 4 }} +{{- end }} diff --git a/k8s/devops-python/templates/servicemonitor.yaml b/k8s/devops-python/templates/servicemonitor.yaml new file mode 100644 index 0000000000..c71b3ca22f --- /dev/null +++ b/k8s/devops-python/templates/servicemonitor.yaml @@ -0,0 +1,20 @@ +{{- if .Values.serviceMonitor.enabled }} +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: {{ include "common.fullname" . }} + labels: + {{- include "common.labels" . | nindent 4 }} + {{- with .Values.serviceMonitor.labels }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + selector: + matchLabels: + {{- include "common.selectorLabels" . | nindent 6 }} + endpoints: + - port: http + path: {{ .Values.serviceMonitor.path }} + interval: {{ .Values.serviceMonitor.interval }} + scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }} +{{- end }} diff --git a/k8s/devops-python/templates/statefulset.yaml b/k8s/devops-python/templates/statefulset.yaml new file mode 100644 index 0000000000..ec45337e52 --- /dev/null +++ b/k8s/devops-python/templates/statefulset.yaml @@ -0,0 +1,150 @@ +{{- if eq .Values.workload.type "statefulset" }} +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "common.fullname" . }} + labels: + {{- include "common.labels" . | nindent 4 }} +spec: + serviceName: {{ include "common.fullname" . }}-headless + replicas: {{ .Values.replicaCount }} + podManagementPolicy: {{ .Values.statefulset.podManagementPolicy }} + selector: + matchLabels: + {{- include "common.selectorLabels" . | nindent 6 }} + updateStrategy: + type: {{ .Values.statefulset.updateStrategy.type }} + {{- if and (eq .Values.statefulset.updateStrategy.type "RollingUpdate") (ne .Values.statefulset.updateStrategy.partition nil) }} + rollingUpdate: + partition: {{ .Values.statefulset.updateStrategy.partition }} + {{- end }} + template: + metadata: + labels: + {{- include "common.selectorLabels" . | nindent 8 }} + annotations: + checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} + {{- if .Values.vault.enabled }} + vault.hashicorp.com/agent-inject: "true" + vault.hashicorp.com/role: {{ .Values.vault.role | quote }} + vault.hashicorp.com/agent-inject-secret-config.txt: {{ .Values.vault.secretPath | quote }} + {{- end }} + spec: + serviceAccountName: {{ default (include "common.fullname" .) .Values.serviceAccount.name }} + volumes: + - name: config-volume + configMap: + name: {{ include "common.fullname" . }}-config + {{- if .Values.initContainers.enabled }} + - name: init-workdir + emptyDir: {} + {{- end }} + {{- if .Values.persistence.enabled }} + initContainers: + - name: volume-permissions + image: busybox:1.36.1 + command: + - sh + - -c + - mkdir -p /data && chown -R 999:999 /data + volumeMounts: + - name: data-volume + mountPath: /data + {{- if .Values.initContainers.waitForService.enabled }} + - name: wait-for-service + image: {{ .Values.initContainers.waitForService.image }} + command: + - sh + - -c + - until nslookup {{ .Values.initContainers.waitForService.host }}; do echo waiting for {{ .Values.initContainers.waitForService.host }}; sleep 2; done + {{- end }} + {{- if .Values.initContainers.download.enabled }} + - name: init-download + image: {{ .Values.initContainers.download.image }} + command: + - sh + - -c + - wget -O {{ .Values.initContainers.sharedMountPath }}/{{ .Values.initContainers.download.outputFile }} {{ .Values.initContainers.download.url }} + volumeMounts: + - name: init-workdir + mountPath: {{ .Values.initContainers.sharedMountPath }} + {{- end }} + {{- else if .Values.initContainers.enabled }} + initContainers: + {{- if .Values.initContainers.waitForService.enabled }} + - name: wait-for-service + image: {{ .Values.initContainers.waitForService.image }} + command: + - sh + - -c + - until nslookup {{ .Values.initContainers.waitForService.host }}; do echo waiting for {{ .Values.initContainers.waitForService.host }}; sleep 2; done + {{- end }} + {{- if .Values.initContainers.download.enabled }} + - name: init-download + image: {{ .Values.initContainers.download.image }} + command: + - sh + - -c + - wget -O {{ .Values.initContainers.sharedMountPath }}/{{ .Values.initContainers.download.outputFile }} {{ .Values.initContainers.download.url }} + volumeMounts: + - name: init-workdir + mountPath: {{ .Values.initContainers.sharedMountPath }} + {{- end }} + {{- end }} + containers: + - name: app + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.container.port }} + protocol: TCP + volumeMounts: + - name: config-volume + mountPath: /config + readOnly: true + {{- if .Values.persistence.enabled }} + - name: data-volume + mountPath: /data + {{- end }} + {{- if .Values.initContainers.enabled }} + - name: init-workdir + mountPath: {{ .Values.initContainers.sharedMountPath }} + {{- end }} + envFrom: + - configMapRef: + name: {{ include "common.fullname" . }}-env + - secretRef: + name: {{ include "common.fullname" . }}-secret + env: + {{- range .Values.env }} + - name: {{ .name }} + value: {{ .value | quote }} + {{- end }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.livenessProbe }} + livenessProbe: + {{- toYaml . | nindent 12 }} + {{- end }} + {{- with .Values.readinessProbe }} + readinessProbe: + {{- toYaml . | nindent 12 }} + {{- end }} + {{- if .Values.persistence.enabled }} + volumeClaimTemplates: + - metadata: + name: data-volume + labels: + {{- include "common.labels" . | nindent 10 }} + spec: + accessModes: + - {{ .Values.persistence.accessMode }} + resources: + requests: + storage: {{ .Values.persistence.size }} + {{- if .Values.persistence.storageClass }} + storageClassName: {{ .Values.persistence.storageClass | quote }} + {{- end }} + {{- end }} +{{- end }} diff --git a/k8s/devops-python/values-bluegreen-update.yaml b/k8s/devops-python/values-bluegreen-update.yaml new file mode 100644 index 0000000000..68e5b45481 --- /dev/null +++ b/k8s/devops-python/values-bluegreen-update.yaml @@ -0,0 +1,33 @@ +replicaCount: 4 + +service: + type: NodePort + nodePort: 32090 + +configFile: + environment: "green-preview" + +configEnv: + APP_ENV: "green-preview" + LOG_LEVEL: "debug" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +rollout: + strategy: blueGreen + blueGreen: + autoPromotionEnabled: false + autoPromotionSeconds: null + scaleDownDelaySeconds: 30 + previewReplicaCount: 2 + previewService: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: 32091 + analysis: + enabled: false diff --git a/k8s/devops-python/values-bluegreen.yaml b/k8s/devops-python/values-bluegreen.yaml new file mode 100644 index 0000000000..00bb71fd35 --- /dev/null +++ b/k8s/devops-python/values-bluegreen.yaml @@ -0,0 +1,33 @@ +replicaCount: 4 + +service: + type: NodePort + nodePort: 32090 + +configFile: + environment: "blue-active" + +configEnv: + APP_ENV: "blue-active" + LOG_LEVEL: "info" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +rollout: + strategy: blueGreen + blueGreen: + autoPromotionEnabled: false + autoPromotionSeconds: null + scaleDownDelaySeconds: 30 + previewReplicaCount: 2 + previewService: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: 32091 + analysis: + enabled: false diff --git a/k8s/devops-python/values-canary-analysis-fail.yaml b/k8s/devops-python/values-canary-analysis-fail.yaml new file mode 100644 index 0000000000..0a8c317d3b --- /dev/null +++ b/k8s/devops-python/values-canary-analysis-fail.yaml @@ -0,0 +1,39 @@ +replicaCount: 5 + +service: + type: NodePort + nodePort: 32080 + +configFile: + environment: "canary-analysis-fail" + +configEnv: + APP_ENV: "canary-analysis-fail" + LOG_LEVEL: "warning" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +rollout: + strategy: canary + analysis: + enabled: true + interval: 10s + count: 3 + failureLimit: 1 + path: /missing + canary: + maxSurge: 25% + maxUnavailable: 0 + steps: + - setWeight: 20 + - analysis: + templates: + - templateName: lab14-canary-devops-python-success-rate + - setWeight: 50 + - pause: + duration: 30s + - setWeight: 100 diff --git a/k8s/devops-python/values-canary-update.yaml b/k8s/devops-python/values-canary-update.yaml new file mode 100644 index 0000000000..5935ed922b --- /dev/null +++ b/k8s/devops-python/values-canary-update.yaml @@ -0,0 +1,39 @@ +replicaCount: 5 + +service: + type: NodePort + nodePort: 32080 + +configFile: + environment: "canary-release" + +configEnv: + APP_ENV: "canary-release" + LOG_LEVEL: "debug" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +rollout: + strategy: canary + analysis: + enabled: false + canary: + maxSurge: 25% + maxUnavailable: 0 + steps: + - setWeight: 20 + - pause: {} + - setWeight: 40 + - pause: + duration: 30s + - setWeight: 60 + - pause: + duration: 30s + - setWeight: 80 + - pause: + duration: 30s + - setWeight: 100 diff --git a/k8s/devops-python/values-canary.yaml b/k8s/devops-python/values-canary.yaml new file mode 100644 index 0000000000..2b9db640ee --- /dev/null +++ b/k8s/devops-python/values-canary.yaml @@ -0,0 +1,39 @@ +replicaCount: 5 + +service: + type: NodePort + nodePort: 32080 + +configFile: + environment: "canary-stable" + +configEnv: + APP_ENV: "canary-stable" + LOG_LEVEL: "info" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +rollout: + strategy: canary + analysis: + enabled: false + canary: + maxSurge: 25% + maxUnavailable: 0 + steps: + - setWeight: 20 + - pause: {} + - setWeight: 40 + - pause: + duration: 30s + - setWeight: 60 + - pause: + duration: 30s + - setWeight: 80 + - pause: + duration: 30s + - setWeight: 100 diff --git a/k8s/devops-python/values-dev.yaml b/k8s/devops-python/values-dev.yaml new file mode 100644 index 0000000000..5e8fc50af3 --- /dev/null +++ b/k8s/devops-python/values-dev.yaml @@ -0,0 +1,35 @@ +replicaCount: 1 + +image: + tag: "v2" + +service: + type: NodePort + +resources: + requests: + cpu: 50m + memory: 64Mi + limits: + cpu: 100m + memory: 128Mi + +livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 10 + +readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 3 + periodSeconds: 5 + +configFile: + environment: "development" + +configEnv: + APP_ENV: "development" diff --git a/k8s/devops-python/values-monitoring.yaml b/k8s/devops-python/values-monitoring.yaml new file mode 100644 index 0000000000..46ef1c5903 --- /dev/null +++ b/k8s/devops-python/values-monitoring.yaml @@ -0,0 +1,57 @@ +workload: + type: statefulset + +replicaCount: 3 + +image: + tag: "lab15" + +service: + type: NodePort + nodePort: 32160 + +serviceMonitor: + enabled: true + labels: + release: monitoring + interval: 15s + scrapeTimeout: 10s + path: /metrics + +configFile: + environment: "monitoring" + +configEnv: + APP_ENV: "monitoring" + LOG_LEVEL: "info" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +persistence: + enabled: true + size: 100Mi + storageClass: "" + accessMode: ReadWriteOnce + +initContainers: + enabled: true + sharedMountPath: /init-data + waitForService: + enabled: true + image: busybox:1.36.1 + host: monitoring-grafana.monitoring.svc.cluster.local + download: + enabled: true + image: busybox:1.36.1 + url: http://monitoring-grafana.monitoring.svc/login + outputFile: grafana-login.html + +statefulset: + podManagementPolicy: OrderedReady + updateStrategy: + type: RollingUpdate + partition: null diff --git a/k8s/devops-python/values-prod.yaml b/k8s/devops-python/values-prod.yaml new file mode 100644 index 0000000000..fe3a561c4e --- /dev/null +++ b/k8s/devops-python/values-prod.yaml @@ -0,0 +1,35 @@ +replicaCount: 5 + +image: + tag: "v2" + +service: + type: LoadBalancer + +resources: + requests: + cpu: 200m + memory: 256Mi + limits: + cpu: 500m + memory: 512Mi + +livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 30 + periodSeconds: 5 + +readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 10 + periodSeconds: 3 + +configFile: + environment: "production" + +configEnv: + APP_ENV: "production" diff --git a/k8s/devops-python/values-statefulset-ondelete.yaml b/k8s/devops-python/values-statefulset-ondelete.yaml new file mode 100644 index 0000000000..e5695318e2 --- /dev/null +++ b/k8s/devops-python/values-statefulset-ondelete.yaml @@ -0,0 +1,35 @@ +workload: + type: statefulset + +replicaCount: 3 + +image: + tag: "lab15" + +service: + type: NodePort + nodePort: 32150 + +configFile: + environment: "statefulset-ondelete" + +configEnv: + APP_ENV: "statefulset-ondelete" + LOG_LEVEL: "warning" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +persistence: + enabled: true + size: 100Mi + storageClass: "" + accessMode: ReadWriteOnce + +statefulset: + podManagementPolicy: OrderedReady + updateStrategy: + type: OnDelete diff --git a/k8s/devops-python/values-statefulset-partition.yaml b/k8s/devops-python/values-statefulset-partition.yaml new file mode 100644 index 0000000000..0b3a914640 --- /dev/null +++ b/k8s/devops-python/values-statefulset-partition.yaml @@ -0,0 +1,36 @@ +workload: + type: statefulset + +replicaCount: 3 + +image: + tag: "lab15" + +service: + type: NodePort + nodePort: 32150 + +configFile: + environment: "statefulset-partition" + +configEnv: + APP_ENV: "statefulset-partition" + LOG_LEVEL: "debug" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +persistence: + enabled: true + size: 100Mi + storageClass: "" + accessMode: ReadWriteOnce + +statefulset: + podManagementPolicy: OrderedReady + updateStrategy: + type: RollingUpdate + partition: 2 diff --git a/k8s/devops-python/values-statefulset.yaml b/k8s/devops-python/values-statefulset.yaml new file mode 100644 index 0000000000..05b087ff28 --- /dev/null +++ b/k8s/devops-python/values-statefulset.yaml @@ -0,0 +1,36 @@ +workload: + type: statefulset + +replicaCount: 3 + +image: + tag: "lab15" + +service: + type: NodePort + nodePort: 32150 + +configFile: + environment: "statefulset" + +configEnv: + APP_ENV: "statefulset" + LOG_LEVEL: "info" + +hooks: + preInstall: + enabled: false + postInstall: + enabled: false + +persistence: + enabled: true + size: 100Mi + storageClass: "" + accessMode: ReadWriteOnce + +statefulset: + podManagementPolicy: OrderedReady + updateStrategy: + type: RollingUpdate + partition: null diff --git a/k8s/devops-python/values.yaml b/k8s/devops-python/values.yaml new file mode 100644 index 0000000000..408aff5c33 --- /dev/null +++ b/k8s/devops-python/values.yaml @@ -0,0 +1,155 @@ +nameOverride: "" +fullnameOverride: "" + +replicaCount: 3 + +image: + repository: s3rap1s/devops-info-service + tag: "v2" + pullPolicy: IfNotPresent + +service: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: null + +serviceMonitor: + enabled: false + labels: + release: monitoring + interval: 30s + scrapeTimeout: 10s + path: /metrics + +container: + port: 5000 + +env: + - name: PORT + value: "5000" + - name: HOST + value: "0.0.0.0" + +configFile: + applicationName: "devops-info-service" + environment: "development" + settings: + featureGreeting: true + maxVisitsDisplay: 10 + +configEnv: + APP_ENV: "development" + LOG_LEVEL: "info" + FEATURE_GREETINGS: "true" + DATA_DIR: "/data" + CONFIG_FILE: "/config/config.json" + +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 200m + memory: 256Mi + +livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 15 + periodSeconds: 10 + +readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 5 + +hooks: + image: busybox:1.36.1 + preInstall: + enabled: true + weight: -5 + postInstall: + enabled: true + weight: 5 + +secret: + create: true + username: "user" + password: "pass" + +serviceAccount: + create: true + name: "" + +vault: + enabled: false + role: "devops-python" + secretPath: "secret/data/myapp/config" + +persistence: + enabled: true + size: 100Mi + storageClass: "" + accessMode: ReadWriteOnce + +workload: + type: rollout + +initContainers: + enabled: false + sharedMountPath: /init-data + waitForService: + enabled: false + image: busybox:1.36.1 + host: monitoring-grafana.monitoring.svc.cluster.local + download: + enabled: false + image: busybox:1.36.1 + url: http://monitoring-grafana.monitoring.svc/login + outputFile: index.html + +rollout: + revisionHistoryLimit: 2 + strategy: canary + canary: + maxSurge: 25% + maxUnavailable: 0 + steps: + - setWeight: 20 + - pause: {} + - setWeight: 40 + - pause: + duration: 30s + - setWeight: 60 + - pause: + duration: 30s + - setWeight: 80 + - pause: + duration: 30s + - setWeight: 100 + blueGreen: + autoPromotionEnabled: false + autoPromotionSeconds: null + scaleDownDelaySeconds: 30 + previewReplicaCount: 1 + previewService: + type: NodePort + port: 80 + targetPort: 5000 + nodePort: null + analysis: + enabled: false + interval: 10s + count: 3 + failureLimit: 1 + path: /health + +statefulset: + podManagementPolicy: OrderedReady + updateStrategy: + type: RollingUpdate + partition: null diff --git a/k8s/go-deployment.yml b/k8s/go-deployment.yml new file mode 100644 index 0000000000..bd2d47ecbc --- /dev/null +++ b/k8s/go-deployment.yml @@ -0,0 +1,50 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: devops-go + labels: + app: devops-go +spec: + replicas: 3 + selector: + matchLabels: + app: devops-go + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + template: + metadata: + labels: + app: devops-go + spec: + containers: + - name: app + image: s3rap1s/devops-info-service-go:latest + ports: + - containerPort: 5000 + env: + - name: PORT + value: "5000" + - name: HOST + value: "0.0.0.0" + resources: + requests: + memory: "64Mi" + cpu: "100m" + limits: + memory: "128Mi" + cpu: "200m" + livenessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 10 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /health + port: 5000 + initialDelaySeconds: 5 + periodSeconds: 5 diff --git a/k8s/go-service.yml b/k8s/go-service.yml new file mode 100644 index 0000000000..317e2fc3ec --- /dev/null +++ b/k8s/go-service.yml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: devops-go-service +spec: + type: ClusterIP + selector: + app: devops-go + ports: + - protocol: TCP + port: 80 + targetPort: 5000 diff --git a/k8s/ingress.yml b/k8s/ingress.yml new file mode 100644 index 0000000000..c78d2a344c --- /dev/null +++ b/k8s/ingress.yml @@ -0,0 +1,31 @@ +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: devops-apps-ingress + annotations: + nginx.ingress.kubernetes.io/use-regex: "true" + nginx.ingress.kubernetes.io/rewrite-target: /$2 +spec: + ingressClassName: nginx + tls: + - hosts: + - local.example.com + secretName: tls-secret + rules: + - host: local.example.com + http: + paths: + - path: /app1(/|$)(.*) + pathType: ImplementationSpecific + backend: + service: + name: devops-python-service + port: + number: 80 + - path: /app2(/|$)(.*) + pathType: ImplementationSpecific + backend: + service: + name: devops-go-service + port: + number: 80 diff --git a/k8s/monitoring-values.yaml b/k8s/monitoring-values.yaml new file mode 100644 index 0000000000..a9365a0809 --- /dev/null +++ b/k8s/monitoring-values.yaml @@ -0,0 +1,9 @@ +prometheusOperator: + admissionWebhooks: + enabled: true + tls: + enabled: true + livenessProbe: + timeoutSeconds: 5 + readinessProbe: + timeoutSeconds: 5 diff --git a/k8s/monitoring/screenshots/alertmanager-alerts.png b/k8s/monitoring/screenshots/alertmanager-alerts.png new file mode 100644 index 0000000000..76a7b08a14 Binary files /dev/null and b/k8s/monitoring/screenshots/alertmanager-alerts.png differ diff --git a/k8s/monitoring/screenshots/grafana-default-namespace-pods.png b/k8s/monitoring/screenshots/grafana-default-namespace-pods.png new file mode 100644 index 0000000000..ecc97e35f0 Binary files /dev/null and b/k8s/monitoring/screenshots/grafana-default-namespace-pods.png differ diff --git a/k8s/monitoring/screenshots/grafana-kubelet.png b/k8s/monitoring/screenshots/grafana-kubelet.png new file mode 100644 index 0000000000..6d7587bbaa Binary files /dev/null and b/k8s/monitoring/screenshots/grafana-kubelet.png differ diff --git a/k8s/monitoring/screenshots/grafana-network-default.png b/k8s/monitoring/screenshots/grafana-network-default.png new file mode 100644 index 0000000000..0a3f2d80a2 Binary files /dev/null and b/k8s/monitoring/screenshots/grafana-network-default.png differ diff --git a/k8s/monitoring/screenshots/grafana-node-exporter.png b/k8s/monitoring/screenshots/grafana-node-exporter.png new file mode 100644 index 0000000000..98fe25ce2d Binary files /dev/null and b/k8s/monitoring/screenshots/grafana-node-exporter.png differ diff --git a/k8s/monitoring/screenshots/grafana-pod-resources.png b/k8s/monitoring/screenshots/grafana-pod-resources.png new file mode 100644 index 0000000000..b31554a482 Binary files /dev/null and b/k8s/monitoring/screenshots/grafana-pod-resources.png differ diff --git a/k8s/monitoring/screenshots/prometheus-lab16-metrics.png b/k8s/monitoring/screenshots/prometheus-lab16-metrics.png new file mode 100644 index 0000000000..c31fedfcdf Binary files /dev/null and b/k8s/monitoring/screenshots/prometheus-lab16-metrics.png differ diff --git a/k8s/service.yml b/k8s/service.yml new file mode 100644 index 0000000000..1632897259 --- /dev/null +++ b/k8s/service.yml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: devops-python-service +spec: + type: NodePort + selector: + app: devops-python + ports: + - protocol: TCP + port: 80 + targetPort: 5000 \ No newline at end of file diff --git a/labs/lab18/app_python/Dockerfile b/labs/lab18/app_python/Dockerfile new file mode 100644 index 0000000000..ea426c5081 --- /dev/null +++ b/labs/lab18/app_python/Dockerfile @@ -0,0 +1,56 @@ +# Dockerfile for Python Application with Virtual Environment +FROM python:3.13-slim AS builder + +# Installing system dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc \ + && rm -rf /var/lib/apt/lists/* + +# Installing the working directory +WORKDIR /app + +# Creating a virtual environment +RUN python -m venv /opt/venv + +# Activating the virtual environment +ENV PATH="/opt/venv/bin:$PATH" + +# Copying requirements file +COPY requirements.txt . +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements.txt + +# Final stage: Copying the virtual environment and application code +FROM python:3.13-slim + +# Creating non-root user and group +RUN groupadd -r appgroup && useradd -r -g appgroup appuser + +# Setting the working directory +WORKDIR /app + +# Copying the virtual environment from the builder stage +COPY --from=builder /opt/venv /opt/venv + +# Copying the application code +COPY . . + +# Setting permissions for the application directory +RUN chown -R appuser:appgroup /app && chmod -R 755 /app + +# Switching to non-root user +USER appuser + +# Setting the PATH to include the virtual environment +ENV PATH="/opt/venv/bin:$PATH" + +# Opening the port for the application +EXPOSE 5000 + +# Setting environment variables +ENV HOST=0.0.0.0 +ENV PORT=5000 +ENV PYTHONUNBUFFERED=1 + +# Running the application +CMD ["python", "app.py"] diff --git a/labs/lab18/app_python/README.md b/labs/lab18/app_python/README.md new file mode 100644 index 0000000000..49abede36a --- /dev/null +++ b/labs/lab18/app_python/README.md @@ -0,0 +1,225 @@ +# DevOps Info Service + +## Overview +A Python-based web service designed to furnish details about itself and its operational environment. This service serves as a foundation for subsequent experiments in containerization, continuous integration and continuous deployment (CI/CD), monitoring, and deployment processes. + +## CI/CD Pipeline +![Python CI/CD](https://github.com/s3rap1s/DevOps-Core-Course/actions/workflows/python-ci.yml/badge.svg) + +### Overview +This project uses GitHub Actions for continuous integration and deployment. The pipeline includes: + +1. **Code Quality Checks** + - Linting with flake8 + - Code formatting with black + - Security scanning with Snyk + +2. **Testing** + - Unit tests with pytest + - Test coverage tracking + - 90%+ code coverage requirement + +3. **Docker Build & Deployment** + - Multi-stage Docker builds + - Automated tagging with Calendar Versioning + - Push to Docker Hub + +### Versioning Strategy +We use **Calendar Versioning (CalVer)** with the format `YYYY.MM.MICRO`: + +- **YYYY.MM.DD** - Specific date of build +- **YYYY.MM.MICRO** - Version with micro release number +- **latest** - Most recent stable build + + +## Prerequisites +- Python 3.11 or higher +- pip (Python Package manager) + +## Installation +1. Clone repository: +```bash +# Clone the project +git clone https://github.com/s3rap1s/DevOps-Core-Course.git +cd DevOps-Core-Course/app_python + +# Create virtual environment +python3 -m venv venv +source venv/bin/activate # on Linux / macOs or .\venv\Scripts\Activate.ps1 on windows + +# Install dependencies +pip install -r requirements.txt +``` + +## Running the Application + +```bash +# Default configuration +python app.py + +# With custom port +PORT=8080 python app.py + +# With custom port and host +HOST=127.0.0.1 PORT=3000 python app.py + +# With custom data and config paths +DATA_DIR=./data CONFIG_FILE=./config/config.json python app.py +``` + +## Testing the Application +```bash +pytest # Run all tests +pytest --cov=app --cov-report=term-missing # Run with coverage +``` + +## Docker + +This application is containerized and available as a Docker image. + +### Building the Image Locally + +```bash +docker build -t devops-info-service:latest . +``` + +### Running a Container + +```bash +# Run with default port mapping +docker run -d -p 5000:5000 devops-info-service:latest + +# Run with custom port +docker run -d -p 8080:5000 devops-info-service:latest + +# Run with environment variables +docker run -d -p 3000:3000 -e PORT=3000 -e HOST=0.0.0.0 devops-info-service:latest + +# Run with persistent visits storage +docker run -d -p 5000:5000 \ + -e DATA_DIR=/app/data \ + -v devops-info-service-data:/app/data \ + devops-info-service:latest +``` + +### Pulling from Docker Hub + +```bash +# Pull the latest version +docker pull your-username/devops-info-service:latest + +# Run pulled image +docker run -d -p 5000:5000 your-username/devops-info-service:latest +``` + +### Environment Variables in Docker +When running in Docker, you can pass environment variables using the `-e` flag: + +```bash +docker run -d -p 5000:5000 \ + -e HOST=0.0.0.0 \ + -e PORT=5000 \ + -e DEBUG=false \ + devops-info-service:latest +``` + +## API Endpoints + +### `GET /` +Return comprehensive service and system information: + +```json +{ + "service": { + "name": "devops-info-service", + "version": "2.0.0", + "description": "DevOps course info service", + "framework": "Flask" + }, + "system": { + "hostname": "my-laptop", + "platform": "Linux", + "platform_version": "Ubuntu 24.04", + "architecture": "x86_64", + "cpu_count": 8, + "python_version": "3.13.1" + }, + "runtime": { + "uptime_seconds": 3600, + "uptime_human": "1 hour, 0 minutes", + "current_time": "2026-01-07T14:30:00.000Z", + "timezone": "UTC", + "visits_count": 12 + }, + "request": { + "client_ip": "127.0.0.1", + "user_agent": "curl/7.81.0", + "method": "GET", + "path": "/" + }, + "configuration": { + "file": { + "application_name": "devops-info-service", + "environment": "development", + "settings": { + "featureGreeting": true, + "maxVisitsDisplay": 10 + } + }, + "environment": { + "APP_ENV": "development", + "LOG_LEVEL": "info", + "FEATURE_GREETINGS": "true", + "CONFIG_FILE": "/config/config.json", + "DATA_DIR": "/data" + } + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"}, + {"path": "/visits", "method": "GET", "description": "Visit counter"}, + {"path": "/metrics", "method": "GET", "description": "Prometheus metrics"} + ] +} +``` + +### `GET /health` + +Simple health endpoint for monitoring: + +```json +{ + "status": "healthy", + "timestamp": "2024-01-15T14:30:00.000Z", + "uptime_seconds": 3600 +} +``` + +### `GET /visits` + +Returns the current persisted visit counter: + +```json +{ + "visits": 12, + "file": "/data/visits" +} +``` + + +## Configuration + +| Variable | Default | Description | +| -------- | --------- | ---------------------------- | +| `HOST` | `0.0.0.0` | Network interface to bind | +| `PORT` | `5000` | Port to listen on | +| `DEBUG` | `false` | Enable debug mode | +| `DATA_DIR` | `./data` | Directory used for visits persistence | +| `VISITS_FILE` | `/visits` | File storing visit counter | +| `CONFIG_FILE` | `./config/config.json` | JSON config file path | + +## Persistence + +The root endpoint increments a counter stored in the visits file. The `/visits` endpoint returns the current value without incrementing it. + +For local Docker Compose testing, the application container mounts a persistent volume to keep `/app/data/visits` across container restarts. diff --git a/labs/lab18/app_python/app.py b/labs/lab18/app_python/app.py new file mode 100644 index 0000000000..7b9e0d983b --- /dev/null +++ b/labs/lab18/app_python/app.py @@ -0,0 +1,323 @@ +""" +DevOps Info Service +Main application module +""" + +import os +import socket +import platform +import logging +import time +import json +import tempfile +from threading import Lock +from datetime import datetime, timezone +from flask import Flask, Response, g, jsonify, request +from prometheus_client import CONTENT_TYPE_LATEST, Counter, Gauge, Histogram, generate_latest +from pythonjsonlogger import jsonlogger + +# Flask app initialization +app = Flask(__name__) + +# Configuration via environment variables +HOST = os.getenv("HOST", "0.0.0.0") +PORT = int(os.getenv("PORT", 5000)) +DEBUG = os.getenv("DEBUG", "False").lower() == "true" +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +DATA_DIR = os.getenv("DATA_DIR", os.path.join(BASE_DIR, "data")) +VISITS_FILE = os.getenv("VISITS_FILE", os.path.join(DATA_DIR, "visits")) +CONFIG_FILE = os.getenv("CONFIG_FILE", os.path.join(BASE_DIR, "config", "config.json")) +VISITS_LOCK = Lock() + +# Application startup time +START_TIME = datetime.now(timezone.utc) + +# Prometheus metrics +HTTP_REQUESTS_TOTAL = Counter( + "http_requests_total", + "Total HTTP requests handled by the application", + ["method", "endpoint", "status_code"], +) +HTTP_REQUEST_DURATION_SECONDS = Histogram( + "http_request_duration_seconds", + "Duration of HTTP requests in seconds", + ["method", "endpoint", "status_code"], +) +HTTP_REQUESTS_IN_PROGRESS = Gauge( + "http_requests_in_progress", + "HTTP requests currently being processed", + ["method", "endpoint"], +) +ENDPOINT_CALLS_TOTAL = Counter( + "devops_info_endpoint_calls_total", + "Total calls to application endpoints", + ["endpoint"], +) +SYSTEM_INFO_COLLECTION_SECONDS = Histogram( + "devops_info_system_info_collection_seconds", + "Time spent collecting system information", +) + +# Setting up logging +logHandler = logging.StreamHandler() +formatter = jsonlogger.JsonFormatter( + fmt='%(asctime)s %(levelname)s %(name)s %(message)s', + datefmt='%Y-%m-%dT%H:%M:%S%z' +) +logHandler.setFormatter(formatter) +logger = logging.getLogger() +logger.addHandler(logHandler) +logger.setLevel(logging.INFO) + + +def ensure_parent_directory(file_path): + """Ensure the parent directory for a file exists.""" + os.makedirs(os.path.dirname(file_path), exist_ok=True) + + +def read_visits_count(): + """Read the visits counter from disk, defaulting to zero.""" + try: + with open(VISITS_FILE, "r", encoding="utf-8") as visits_file: + raw_value = visits_file.read().strip() + except FileNotFoundError: + return 0 + + if not raw_value: + return 0 + + try: + return int(raw_value) + except ValueError: + logger.warning("Invalid visits counter value, resetting to zero", extra={"file": VISITS_FILE}) + return 0 + + +def write_visits_count(count): + """Persist the visits counter using an atomic file replacement.""" + ensure_parent_directory(VISITS_FILE) + + with tempfile.NamedTemporaryFile( + "w", + encoding="utf-8", + dir=os.path.dirname(VISITS_FILE), + delete=False, + ) as temp_file: + temp_file.write(str(count)) + temp_file.flush() + os.fsync(temp_file.fileno()) + temp_path = temp_file.name + + os.replace(temp_path, VISITS_FILE) + + +def increment_visits_count(): + """Increment the visits counter in a thread-safe way.""" + with VISITS_LOCK: + count = read_visits_count() + 1 + write_visits_count(count) + return count + + +def load_app_config(): + """Load JSON configuration from disk if available.""" + try: + with open(CONFIG_FILE, "r", encoding="utf-8") as config_file: + return json.load(config_file) + except FileNotFoundError: + return {} + except json.JSONDecodeError: + logger.warning("Invalid JSON configuration file", extra={"file": CONFIG_FILE}) + return {} + + +def get_request_endpoint(): + """Return a normalized endpoint label with low cardinality.""" + if request.url_rule and request.url_rule.rule: + return request.url_rule.rule + if request.path == "/metrics": + return "/metrics" + return "unmatched" + + +@app.before_request +def log_request(): + endpoint = get_request_endpoint() + g.request_start_time = time.perf_counter() + g.metrics_endpoint = endpoint + HTTP_REQUESTS_IN_PROGRESS.labels( + method=request.method, + endpoint=endpoint, + ).inc() + logger.info("Request received", extra={ + 'method': request.method, + 'path': request.path, + 'ip': request.remote_addr + }) + +@app.after_request +def log_response(response): + endpoint = getattr(g, "metrics_endpoint", get_request_endpoint()) + HTTP_REQUESTS_TOTAL.labels( + method=request.method, + endpoint=endpoint, + status_code=str(response.status_code), + ).inc() + duration = time.perf_counter() - getattr(g, "request_start_time", time.perf_counter()) + HTTP_REQUEST_DURATION_SECONDS.labels( + method=request.method, + endpoint=endpoint, + status_code=str(response.status_code), + ).observe(duration) + HTTP_REQUESTS_IN_PROGRESS.labels( + method=request.method, + endpoint=endpoint, + ).dec() + logger.info("Response sent", extra={ + 'status': response.status_code, + 'method': request.method, + 'path': request.path + }) + return response + + +def get_system_info(): + """Collecting information about the system. + + Returns: + dict: System configuration + """ + with SYSTEM_INFO_COLLECTION_SECONDS.time(): + return { + "hostname": socket.gethostname(), + "platform": platform.system(), + "platform_version": platform.release(), + "architecture": platform.machine(), + "cpu_count": os.cpu_count() or 0, + "python_version": platform.python_version(), + } + + +def get_uptime(): + """Calculating the running time of the application. + + Returns: + dict: Uptime in seconds and human-readable format + """ + delta = datetime.now(timezone.utc) - START_TIME + seconds = int(delta.total_seconds()) + hours = seconds // 3600 + minutes = (seconds % 3600) // 60 + return {"seconds": seconds, "human": f"{hours} hours, {minutes} minutes"} + + +@app.route("/") +def index(): + """The main endpoint - Information about the service and the system.""" + client_ip = request.remote_addr + user_agent = request.headers.get("User-Agent", "Unknown") + endpoint = get_request_endpoint() + ENDPOINT_CALLS_TOTAL.labels(endpoint=endpoint).inc() + uptime = get_uptime() + system_info = get_system_info() + visits_count = increment_visits_count() + file_config = load_app_config() + + # Forming a response + response = { + "service": { + "name": "devops-info-service", + "version": "2.0.0", + "description": "DevOps course info service", + "framework": "Flask", + }, + "system": system_info, + "runtime": { + "uptime_seconds": uptime["seconds"], + "uptime_human": uptime["human"], + "current_time": datetime.now(timezone.utc).isoformat(), + "timezone": "UTC", + "visits_count": visits_count, + }, + "request": { + "client_ip": client_ip, + "user_agent": user_agent, + "method": request.method, + "path": request.path, + }, + "configuration": { + "file": file_config, + "environment": { + "APP_ENV": os.getenv("APP_ENV", "undefined"), + "LOG_LEVEL": os.getenv("LOG_LEVEL", "undefined"), + "FEATURE_GREETINGS": os.getenv("FEATURE_GREETINGS", "undefined"), + "CONFIG_FILE": CONFIG_FILE, + "DATA_DIR": DATA_DIR, + }, + }, + "endpoints": [ + {"path": "/", "method": "GET", "description": "Service information"}, + {"path": "/health", "method": "GET", "description": "Health check"}, + {"path": "/visits", "method": "GET", "description": "Visit counter"}, + {"path": "/metrics", "method": "GET", "description": "Prometheus metrics"}, + ], + } + return jsonify(response) + + +@app.route("/health") +def health(): + """Endpoint for health check.""" + ENDPOINT_CALLS_TOTAL.labels(endpoint=get_request_endpoint()).inc() + response = { + "status": "healthy", + "timestamp": datetime.now(timezone.utc).isoformat(), + "uptime_seconds": get_uptime()["seconds"], + } + logger.debug(f"Health check: {response}") + return jsonify(response), 200 + + +@app.route("/visits") +def visits(): + """Return the current visits counter without incrementing it.""" + ENDPOINT_CALLS_TOTAL.labels(endpoint=get_request_endpoint()).inc() + response = { + "visits": read_visits_count(), + "file": VISITS_FILE, + } + return jsonify(response), 200 + + +@app.route("/metrics") +def metrics(): + """Expose Prometheus metrics for scraping.""" + ENDPOINT_CALLS_TOTAL.labels(endpoint=get_request_endpoint()).inc() + return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST) + + +@app.errorhandler(404) +def not_found(error): + """Error handler 404.""" + logger.warning(f"404 Not Found: {request.path}") + return jsonify({"error": "Not Found", "message": "Endpoint does not exist"}), 404 + + +@app.errorhandler(500) +def internal_error(error): + """Error handler 500.""" + logger.error(f"500 Internal Server Error: {str(error)}") + return ( + jsonify( + { + "error": "Internal Server Error", + "message": "An unexpected error occurred", + } + ), + 500, + ) + + +if __name__ == "__main__": + logger.info(f"Starting DevOps Info Service on {HOST}:{PORT} (debug={DEBUG})") + app.run(host=HOST, port=PORT, debug=DEBUG) diff --git a/labs/lab18/app_python/default.nix b/labs/lab18/app_python/default.nix new file mode 100644 index 0000000000..a223a3721d --- /dev/null +++ b/labs/lab18/app_python/default.nix @@ -0,0 +1,53 @@ +{ pkgs ? import {} }: + +let + python = pkgs.python313.withPackages (ps: with ps; [ + flask + prometheus-client + python-dotenv + python-json-logger + requests + ]); +in +pkgs.python313Packages.buildPythonApplication { + pname = "devops-info-service"; + version = "2.0.0"; + src = ./.; + + format = "other"; + dontBuild = true; + doCheck = false; + + nativeBuildInputs = [ pkgs.makeWrapper ]; + + propagatedBuildInputs = with pkgs.python313Packages; [ + flask + prometheus-client + python-dotenv + python-json-logger + requests + ]; + + installPhase = '' + runHook preInstall + + mkdir -p $out/share/devops-info-service $out/bin + cp app.py $out/share/devops-info-service/app.py + cp requirements.txt $out/share/devops-info-service/requirements.txt + + makeWrapper ${python}/bin/python $out/bin/devops-info-service \ + --add-flags "$out/share/devops-info-service/app.py" \ + --set-default HOST "0.0.0.0" \ + --set-default PORT "5000" \ + --set-default DATA_DIR "/tmp/devops-info-service/data" \ + --set-default CONFIG_FILE "$out/share/devops-info-service/config/config.json" + + runHook postInstall + ''; + + meta = with pkgs.lib; { + description = "DevOps Info Service from Labs 1-2 built reproducibly with Nix"; + mainProgram = "devops-info-service"; + platforms = platforms.linux; + }; +} diff --git a/labs/lab18/app_python/docker.nix b/labs/lab18/app_python/docker.nix new file mode 100644 index 0000000000..4463a41e2d --- /dev/null +++ b/labs/lab18/app_python/docker.nix @@ -0,0 +1,29 @@ +{ pkgs ? import {} }: + +let + app = import ./default.nix { inherit pkgs; }; +in +pkgs.dockerTools.buildLayeredImage { + name = "devops-info-service-nix"; + tag = "2.0.0"; + + contents = [ + app + pkgs.dockerTools.caCertificates + ]; + + config = { + Cmd = [ "${app}/bin/devops-info-service" ]; + Env = [ + "HOST=0.0.0.0" + "PORT=5000" + "PYTHONUNBUFFERED=1" + "DATA_DIR=/tmp/devops-info-service/data" + ]; + ExposedPorts = { + "5000/tcp" = {}; + }; + }; + + created = "1970-01-01T00:00:01Z"; +} diff --git a/labs/lab18/app_python/flake.lock b/labs/lab18/app_python/flake.lock new file mode 100644 index 0000000000..8008d9f576 --- /dev/null +++ b/labs/lab18/app_python/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1777428379, + "narHash": "sha256-ypxFOeDz+CqADEQNL72haqGjvZQdBR5Vc7pyx2JDttI=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "755f5aa91337890c432639c60b6064bb7fe67769", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-25.11", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/labs/lab18/app_python/flake.nix b/labs/lab18/app_python/flake.nix new file mode 100644 index 0000000000..3f499fbc80 --- /dev/null +++ b/labs/lab18/app_python/flake.nix @@ -0,0 +1,40 @@ +{ + description = "DevOps Info Service reproducible build with Nix"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11"; + }; + + outputs = { nixpkgs, ... }: + let + system = "x86_64-linux"; + pkgs = nixpkgs.legacyPackages.${system}; + app = import ./default.nix { inherit pkgs; }; + dockerImage = import ./docker.nix { inherit pkgs; }; + in + { + packages.${system} = { + default = app; + dockerImage = dockerImage; + }; + + apps.${system}.default = { + type = "app"; + program = "${app}/bin/devops-info-service"; + }; + + devShells.${system}.default = pkgs.mkShell { + packages = [ + (pkgs.python313.withPackages (ps: with ps; [ + flask + prometheus-client + pytest + pytest-cov + python-dotenv + python-json-logger + requests + ])) + ]; + }; + }; +} diff --git a/labs/lab18/app_python/requirements.txt b/labs/lab18/app_python/requirements.txt new file mode 100644 index 0000000000..7bd58ef8fb --- /dev/null +++ b/labs/lab18/app_python/requirements.txt @@ -0,0 +1,14 @@ +# Web framework +Flask==3.1.0 + +# Testing +pytest==8.1.1 +pytest-cov==5.0.0 +requests==2.31.0 + +# Logging framework +python-json-logger==2.0.7 +prometheus-client==0.23.1 + +# Virtual environment for python +python-dotenv==1.0.1 diff --git a/labs/lab18/app_python/tests/__init__.py b/labs/lab18/app_python/tests/__init__.py new file mode 100644 index 0000000000..be62617d4e --- /dev/null +++ b/labs/lab18/app_python/tests/__init__.py @@ -0,0 +1 @@ +# Unit tests (Lab 3) diff --git a/labs/lab18/app_python/tests/test_app.py b/labs/lab18/app_python/tests/test_app.py new file mode 100644 index 0000000000..ccc88ee490 --- /dev/null +++ b/labs/lab18/app_python/tests/test_app.py @@ -0,0 +1,254 @@ +import pytest +import sys +import os +import json + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) +import app as app_module + +app = app_module.app + + +@pytest.fixture +def client(tmp_path, monkeypatch): + """Fixture for test client Flask""" + visits_file = tmp_path / "visits" + config_file = tmp_path / "config.json" + config_file.write_text( + json.dumps( + { + "application_name": "test-devops-service", + "environment": "test", + "settings": { + "featureGreeting": True, + "maxVisitsDisplay": 10, + }, + } + ), + encoding="utf-8", + ) + monkeypatch.setattr(app_module, "DATA_DIR", str(tmp_path)) + monkeypatch.setattr(app_module, "VISITS_FILE", str(visits_file)) + monkeypatch.setattr(app_module, "CONFIG_FILE", str(config_file)) + with app.test_client() as client: + yield client + + +def test_get_system_info(): + """Test of get_system_info()""" + from app import get_system_info + + info = get_system_info() + + assert isinstance(info, dict) + assert "hostname" in info + assert "platform" in info + assert "python_version" in info + assert isinstance(info["cpu_count"], int) + + +def test_get_uptime(): + """Test of get_uptime()""" + from app import get_uptime + + uptime = get_uptime() + + assert isinstance(uptime, dict) + assert "seconds" in uptime + assert "human" in uptime + assert isinstance(uptime["seconds"], int) + assert isinstance(uptime["human"], str) + + +def test_main_endpoint(client): + """Test of main endpoint GET /""" + response = client.get("/") + + # Status check + assert response.status_code == 200 + + # Json structure test + data = response.get_json() + + # Service structure test + assert "service" in data + assert data["service"]["name"] == "devops-info-service" + assert data["service"]["version"] == "2.0.0" + assert data["service"]["framework"] == "Flask" + + # System structure test + assert "system" in data + assert all( + key in data["system"] + for key in [ + "hostname", + "platform", + "platform_version", + "architecture", + "cpu_count", + "python_version", + ] + ) + + # Time structure test + assert "runtime" in data + assert "uptime_seconds" in data["runtime"] + assert "current_time" in data["runtime"] + assert data["runtime"]["timezone"] == "UTC" + assert data["runtime"]["visits_count"] == 1 + + # Request structure test + assert "request" in data + assert "client_ip" in data["request"] + assert "method" in data["request"] + assert data["request"]["method"] == "GET" + + assert "configuration" in data + assert data["configuration"]["file"]["application_name"] == "test-devops-service" + assert data["configuration"]["environment"]["CONFIG_FILE"].endswith("config.json") + + # Endpoints structure test + assert "endpoints" in data + assert isinstance(data["endpoints"], list) + assert len(data["endpoints"]) >= 3 + + +def test_health_endpoint(client): + """Test of health endpoint GET /health""" + response = client.get("/health") + + # Status check + assert response.status_code == 200 + + # Json structure test + data = response.get_json() + + assert "status" in data + assert data["status"] == "healthy" + assert "timestamp" in data + assert "uptime_seconds" in data + assert isinstance(data["uptime_seconds"], int) + + +def test_404_error(client): + """404 error handling test""" + response = client.get("/nonexistent") + + assert response.status_code == 404 + + data = response.get_json() + assert "error" in data + assert "message" in data + assert data["error"] == "Not Found" + + +def test_different_user_agent(client): + """Test with different User-Agent headers.""" + headers = {"User-Agent": "Test-Agent/1.0"} + response = client.get("/", headers=headers) + + assert response.status_code == 200 + data = response.get_json() + assert data["request"]["user_agent"] == "Test-Agent/1.0" + + +def test_json_structure_types(client): + """Checking the data types in the JSON response""" + response = client.get("/") + data = response.get_json() + + # Type check in service + assert isinstance(data["service"]["name"], str) + assert isinstance(data["service"]["version"], str) + assert isinstance(data["service"]["description"], str) + + # Type check in system + assert isinstance(data["system"]["hostname"], str) + assert isinstance(data["system"]["cpu_count"], int) + assert isinstance(data["system"]["python_version"], str) + + # Type check in runtime + assert isinstance(data["runtime"]["uptime_seconds"], int) + assert isinstance(data["runtime"]["current_time"], str) + + +def test_health_response_structure(client): + """Detailed verification of the health endpoint structure""" + response = client.get("/health") + data = response.get_json() + + # Checking all required fields + required_fields = ["status", "timestamp", "uptime_seconds"] + for field in required_fields: + assert field in data + + # Checking the status value + assert data["status"] == "healthy" + + # Checking the timestamp format + from datetime import datetime + + try: + datetime.fromisoformat(data["timestamp"].replace("Z", "+00:00")) + timestamp_valid = True + except ValueError: + timestamp_valid = False + assert timestamp_valid + + +def test_metrics_endpoint(client): + """Metrics endpoint exposes Prometheus metrics in text format.""" + client.get("/") + client.get("/health") + + response = client.get("/metrics") + + assert response.status_code == 200 + assert response.mimetype == "text/plain" + + metrics_output = response.get_data(as_text=True) + metric_lines = metrics_output.splitlines() + + assert "http_requests_total" in metrics_output + assert any( + line.startswith("http_requests_total{") + and 'endpoint="/"' in line + and 'method="GET"' in line + and 'status_code="200"' in line + for line in metric_lines + ) + assert any( + line.startswith("http_requests_total{") + and 'endpoint="/health"' in line + and 'method="GET"' in line + and 'status_code="200"' in line + for line in metric_lines + ) + assert "http_request_duration_seconds_bucket" in metrics_output + assert any( + line.startswith("http_requests_in_progress{") + and 'endpoint="/metrics"' in line + and 'method="GET"' in line + for line in metric_lines + ) + assert "devops_info_endpoint_calls_total" in metrics_output + assert "devops_info_system_info_collection_seconds_bucket" in metrics_output + + +def test_visits_endpoint_and_persistence(client): + """The root endpoint increments visits and /visits returns the stored counter.""" + first_response = client.get("/") + second_response = client.get("/") + visits_response = client.get("/visits") + + assert first_response.status_code == 200 + assert second_response.status_code == 200 + assert visits_response.status_code == 200 + + assert first_response.get_json()["runtime"]["visits_count"] == 1 + assert second_response.get_json()["runtime"]["visits_count"] == 2 + assert visits_response.get_json()["visits"] == 2 + assert os.path.exists(app_module.VISITS_FILE) + + with open(app_module.VISITS_FILE, "r", encoding="utf-8") as visits_file: + assert visits_file.read().strip() == "2" diff --git a/labs/lab18/screenshots/docker-containers-side-by-side.png b/labs/lab18/screenshots/docker-containers-side-by-side.png new file mode 100644 index 0000000000..eea4b0ba7c Binary files /dev/null and b/labs/lab18/screenshots/docker-containers-side-by-side.png differ diff --git a/labs/lab18/screenshots/nix-app-running.png b/labs/lab18/screenshots/nix-app-running.png new file mode 100644 index 0000000000..c30b7f17fe Binary files /dev/null and b/labs/lab18/screenshots/nix-app-running.png differ diff --git a/labs/submission18.md b/labs/submission18.md new file mode 100644 index 0000000000..3c896b154f --- /dev/null +++ b/labs/submission18.md @@ -0,0 +1,472 @@ +# Lab 18 - Reproducible Builds with Nix + +## 1. Environment + +Nix was installed with the Determinate Systems installer. + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ nix --version +nix (Determinate Nix 3.19.0) 2.34.6 +``` + +Basic Nix execution was verified: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ nix run nixpkgs#hello +Hello, world! +``` + +The Lab 1 Python application was copied into the required Lab 18 directory: + +```text +labs/lab18/app_python/ +├── app.py +├── requirements.txt +├── Dockerfile +├── default.nix +├── docker.nix +├── flake.nix +└── flake.lock +``` + +## 2. Nix Build for the Python App + +The Nix derivation is stored in `labs/lab18/app_python/default.nix`. + +Important fields: + +| Field | Purpose | +| --- | --- | +| `pname` / `version` | Names the built package as `devops-info-service-2.0.0`. | +| `src = ./.` | Uses the copied Lab 1 app as the source input. | +| `format = "other"` | The app does not use `setup.py` or `pyproject.toml`. | +| `python313.withPackages` | Builds a fixed Python runtime with Flask, Prometheus, dotenv, requests, and JSON logging packages from nixpkgs. | +| `makeWrapper` | Creates `bin/devops-info-service`, so the app can run without relying on system Python. | +| `--set-default` env vars | Provides default runtime values while still allowing overrides such as `PORT=5002`. | + +Key part of the derivation: + +```nix +let + python = pkgs.python313.withPackages (ps: with ps; [ + flask + prometheus-client + python-dotenv + python-json-logger + requests + ]); +in +pkgs.python313Packages.buildPythonApplication { + pname = "devops-info-service"; + version = "2.0.0"; + src = ./.; + format = "other"; + dontBuild = true; + doCheck = false; + nativeBuildInputs = [ pkgs.makeWrapper ]; +} +``` + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build --print-out-paths +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +``` + +The wrapped executable uses Python from the Nix store: + +```text +exec "/nix/store/qag75plci0xx1sfi6g9n8425brd8iizw-python3-3.13.12-env/bin/python" \ + /nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0/share/devops-info-service/app.py +``` + +### Reproducibility Check + +Two normal builds produced the same store path and output hash: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ rm -f result +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build --print-out-paths +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ readlink result +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix-hash --type sha256 result +1ab05436a298c01b861516049a798b4fc48559b8f3337727bcd153f949d5fce0 + +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ rm -f result +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build --print-out-paths +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ readlink result +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix-hash --type sha256 result +1ab05436a298c01b861516049a798b4fc48559b8f3337727bcd153f949d5fce0 +``` + +Then the output path was deleted from the Nix store and rebuilt: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ STORE_PATH=$(readlink result) +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ rm -f result +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix-store --delete "$STORE_PATH" +deleting '/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0' +1 store paths deleted, 10.7 KiB freed +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build --print-out-paths +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ readlink result +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix-hash --type sha256 result +1ab05436a298c01b861516049a798b4fc48559b8f3337727bcd153f949d5fce0 +``` + +The same output path and hash returned after a real rebuild. This proves the build output is reproducible for the same locked inputs. + +### Running the Nix-Built App + +The app was started from the Nix output: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ PORT=5002 ./result/bin/devops-info-service +``` + +Health check: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ curl -s http://127.0.0.1:5002/health +{"status":"healthy","timestamp":"2026-05-01T19:36:30.897663+00:00","uptime_seconds":8} +``` + +Screenshot: + +![Nix app running](lab18/screenshots/nix-app-running.png) + +### Store Path Format + +```text +/nix/store/3wgpmaydm9bxq98g4sykwxybbz54fy42-devops-info-service-2.0.0 +``` + +| Part | Meaning | +| --- | --- | +| `/nix/store` | Immutable Nix store location. | +| `3wgpmaydm9bxq98g4sykwxybbz54fy42` | Hash derived from all build inputs and instructions. | +| `devops-info-service` | Package name from `pname`. | +| `2.0.0` | Package version from the derivation. | + +Same inputs produce the same hash prefix and store path. If source code, dependencies, build instructions, or nixpkgs revision change, the store path changes. + +## 3. Lab 1 `pip` vs Nix + +The Lab 1 workflow was: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 λ python -m venv venv +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 λ source venv/bin/activate +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 λ pip install -r requirements.txt +s3rap1s in ~/devops/DevOps-Core-Course/app_python on lab01 λ python app.py +``` + +The current `requirements.txt` pins direct dependencies such as `Flask==3.1.0`, `pytest==8.1.1`, and `requests==2.31.0`, but not the full dependency closure. During the Dockerfile build, `pip` resolved transitive dependencies at build time: + +```text +Werkzeug-3.1.8 +Jinja2-3.1.6 +click-8.3.3 +certifi-2026.4.22 +coverage-7.13.5 +urllib3-2.6.3 +``` + +That means future builds can change when PyPI packages or available wheels change, even if the direct requirement lines stay the same. Nix instead uses packages from the pinned `nixpkgs` revision in `flake.lock`. + +| Aspect | Lab 1: pip + venv | Lab 18: Nix | +| --- | --- | --- | +| Python version | Depends on local system or base image | Pinned by nixpkgs: Python 3.13.12 | +| Dependency source | PyPI at install time | Pinned nixpkgs revision | +| Transitive dependencies | Resolved by pip during install | Locked in the Nix closure | +| Build output | No stable store path | Stable `/nix/store/...` path | +| Rebuild behavior | Can drift over time | Same inputs produce same output | + +Reflection: Nix would have helped in Lab 1 by making the development and runtime environment explicit from the start. The app would not depend on whichever Python, pip, or transitive packages were available on the machine at install time. + +## 4. Reproducible Docker Image with Nix + +The Docker image expression is stored in `labs/lab18/app_python/docker.nix`. + +Important fields: + +| Field | Purpose | +| --- | --- | +| `app = import ./default.nix` | Reuses the reproducible Python derivation. | +| `buildLayeredImage` | Builds an OCI/Docker image from Nix store paths. | +| `contents = [ app pkgs.dockerTools.caCertificates ]` | Includes the app closure and CA certificates. | +| `config.Cmd` | Runs the Nix-built app inside the container. | +| `created = "1970-01-01T00:00:01Z"` | Uses a fixed timestamp to avoid timestamp-based image drift. | + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build .#dockerImage --print-out-paths +/nix/store/5imlckywy44nlw0nrg776rcb4h7s96is-devops-info-service-nix.tar.gz +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ sha256sum result +546860039d0ea982f9a444563f5b99bc48baba68e2355387e43c278a18508566 result +``` + +Two builds produced the same tarball path and SHA256: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ rm -f result +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build .#dockerImage --print-out-paths +/nix/store/5imlckywy44nlw0nrg776rcb4h7s96is-devops-info-service-nix.tar.gz +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ sha256sum result +546860039d0ea982f9a444563f5b99bc48baba68e2355387e43c278a18508566 result + +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ rm -f result +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build .#dockerImage --print-out-paths +/nix/store/5imlckywy44nlw0nrg776rcb4h7s96is-devops-info-service-nix.tar.gz +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ sha256sum result +546860039d0ea982f9a444563f5b99bc48baba68e2355387e43c278a18508566 result +``` + +The image was loaded into Docker: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ docker load --input result +Loaded image: devops-info-service-nix:2.0.0 +``` + +Image metadata: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker image inspect devops-info-service-nix:2.0.0 --format '{{.Id}} {{.Created}} {{.Size}}' +sha256:b6b2d13f01387b396db25ab5b182e96781ca8400fb553e93ba16a8c547a37e4a 1970-01-01T00:00:01Z 203835247 +``` + +The fixed `Created` timestamp confirms that `dockerTools` did not inject the current build time into the image metadata. + +## 5. Lab 2 Dockerfile Comparison + +The Lab 2 Dockerfile uses a traditional flow: + +```dockerfile +FROM python:3.13-slim AS builder +RUN apt-get update && apt-get install -y --no-install-recommends gcc +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements.txt +FROM python:3.13-slim +COPY --from=builder /opt/venv /opt/venv +COPY . . +CMD ["python", "app.py"] +``` + +The base image was pulled by tag: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker pull python:3.13-slim +3.13-slim: Pulling from library/python +Digest: sha256:a0779d7c12fc20be6ec6b4ddc901a4fd7657b8a6bc9def9d3fde89ed5efe0a3d +Status: Downloaded newer image for python:3.13-slim +docker.io/library/python:3.13-slim +``` + +Two no-cache Dockerfile builds produced different image IDs, timestamps, sizes, and exported tarball hashes: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker build --no-cache -t lab2-app:test1 ./app_python +... +Successfully installed Flask-3.1.0 Jinja2-3.1.6 MarkupSafe-3.0.3 Werkzeug-3.1.8 blinker-1.9.0 certifi-2026.4.22 charset-normalizer-3.4.7 click-8.3.3 coverage-7.13.5 idna-3.13 iniconfig-2.3.0 itsdangerous-2.2.0 packaging-26.2 pluggy-1.6.0 prometheus-client-0.23.1 pytest-8.1.1 pytest-cov-5.0.0 python-dotenv-1.0.1 python-json-logger-2.0.7 requests-2.31.0 urllib3-2.6.3 +... +exporting manifest list sha256:d604541d953d8a196acb78316280884313510f24652ed54e1e33f3212306797b + +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker build --no-cache -t lab2-app:test2 ./app_python +... +Successfully installed Flask-3.1.0 Jinja2-3.1.6 MarkupSafe-3.0.3 Werkzeug-3.1.8 blinker-1.9.0 certifi-2026.4.22 charset-normalizer-3.4.7 click-8.3.3 coverage-7.13.5 idna-3.13 iniconfig-2.3.0 itsdangerous-2.2.0 packaging-26.2 pluggy-1.6.0 prometheus-client-0.23.1 pytest-8.1.1 pytest-cov-5.0.0 python-dotenv-1.0.1 python-json-logger-2.0.7 requests-2.31.0 urllib3-2.6.3 +... +exporting manifest list sha256:300999c0553b87714d9af0d8f5b35de3b28f4d421d21d200d8548f3d92fe6ad9 + +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker image inspect lab2-app:test1 --format '{{.Id}} {{.Created}} {{.Size}}' +sha256:d604541d953d8a196acb78316280884313510f24652ed54e1e33f3212306797b 2026-05-01T23:03:22.603553241+03:00 51369316 +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker save lab2-app:test1 | sha256sum +538ac87988e453a04d9835735385eae649febd761f7687c15dcbfba1de7d9ab4 - + +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker image inspect lab2-app:test2 --format '{{.Id}} {{.Created}} {{.Size}}' +sha256:300999c0553b87714d9af0d8f5b35de3b28f4d421d21d200d8548f3d92fe6ad9 2026-05-01T23:06:00.049443662+03:00 51369700 +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker save lab2-app:test2 | sha256sum +a51b1fe74d813ecba93c70b515bdbf763cb4c062ce4bff47eef72e7f10d14351 - +``` + +The Dockerfile builds also downloaded from Debian repositories and PyPI during the build. For example, pip resolved current transitive packages such as `Werkzeug-3.1.8` and `certifi-2026.4.22`. + +### Side-by-Side Containers + +The traditional and Nix-built images were run at the same time: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker run -d -p 5010:5000 --name lab18-lab2-container devops-info-service:python +e66241307c55af64c3b5990bfc4289fc2790c3ad575f3f47b15e10fd53c15aa4 +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker run -d -p 5011:5000 --name lab18-nix-container devops-info-service-nix:2.0.0 +b1622117c320e5ddedb95ff9cc0bac32913622a13aaeab2ef9304c35dfea3734 +``` + +Container status: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Ports}}' | grep lab18 +lab18-lab2-container devops-info-service:python 0.0.0.0:5010->5000/tcp +lab18-nix-container devops-info-service-nix:2.0.0 0.0.0.0:5011->5000/tcp +``` + +Health checks: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ curl -s http://127.0.0.1:5010/health +{"status":"healthy","timestamp":"2026-05-01T19:52:12.866892+00:00","uptime_seconds":367} +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ curl -s http://127.0.0.1:5011/health +{"status":"healthy","timestamp":"2026-05-01T19:52:12.943136+00:00","uptime_seconds":369} +``` + +Screenshot: + +![Docker containers side by side](lab18/screenshots/docker-containers-side-by-side.png) + +### Image Size and History + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker images --format 'table {{.Repository}}:{{.Tag}}\t{{.ID}}\t{{.Size}}' | grep -E 'devops-info-service:python|devops-info-service-nix:2.0.0' +devops-info-service:python 4b08b6e2f063 199MB +devops-info-service-nix:2.0.0 b6b2d13f0138 420MB +``` + +The Nix image is larger in this implementation because it carries the full Python/Nix closure as store paths. The benefit is stronger reproducibility, not smaller size. + +Traditional image history contains relative build timestamps: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker history --format 'table {{.CreatedSince}}\t{{.Size}}\t{{.Comment}}' devops-info-service:python | head -n 4 +CREATED SIZE COMMENT +3 months ago 0B buildkit.dockerfile.v0 +3 months ago 0B buildkit.dockerfile.v0 +3 months ago 16.4kB buildkit.dockerfile.v0 +``` + +Nix image history is based on store path layers: +```bash +s3rap1s in ~/devops/DevOps-Core-Course on lab18 λ docker history --format 'table {{.CreatedSince}}\t{{.Size}}\t{{.Comment}}' devops-info-service-nix:2.0.0 | head -n 4 +CREATED SIZE COMMENT +N/A 73.7kB store paths: ['/nix/store/f60vdjrp...-customisation-layer'] +N/A 57.3kB store paths: ['/nix/store/3wgpmayd...-devops-info-service-2.0.0'] +N/A 1.22MB store paths: ['/nix/store/qag75plc...-python3-3.13.12-env'] +``` + +| Metric | Lab 2 Dockerfile | Lab 18 Nix dockerTools | +| --- | --- | --- | +| Build input | Dockerfile, mutable tags, Debian repos, PyPI | Nix derivations and locked nixpkgs | +| Timestamp | Current build timestamp | Fixed `1970-01-01T00:00:01Z` | +| Rebuild hash | Different tar hashes | Identical tar hash | +| Runtime result | Healthy Flask app | Healthy Flask app | +| Image size in this lab | 199MB | 420MB | + +Why Dockerfile builds are not bit-for-bit reproducible: + +- `python:3.13-slim` is a tag and can point to different content over time. +- `apt-get update` uses current Debian repository state. +- `pip install` resolves transitive dependencies during the build. +- Build metadata includes current timestamps. +- Docker layer cache behavior depends on local daemon state. + +Reflection: If Lab 2 were redone with Nix, I would build the app once as a Nix derivation, build the container from the same derivation with `dockerTools`, and push images by digest rather than relying only on mutable tags. + +## 6. Flake Bonus + +The project was converted to a Nix flake in `labs/lab18/app_python/flake.nix`. + +Important parts: + +```nix +inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11"; +}; + +outputs = { nixpkgs, ... }: + let + system = "x86_64-linux"; + pkgs = nixpkgs.legacyPackages.${system}; + app = import ./default.nix { inherit pkgs; }; + dockerImage = import ./docker.nix { inherit pkgs; }; + in { + packages.${system}.default = app; + packages.${system}.dockerImage = dockerImage; + devShells.${system}.default = pkgs.mkShell { + packages = [ + (pkgs.python313.withPackages (ps: with ps; [ + flask prometheus-client pytest pytest-cov python-dotenv python-json-logger requests + ])) + ]; + }; + }; +``` + +`flake.lock` pins the exact nixpkgs revision: + +```json +{ + "locked": { + "lastModified": 1777428379, + "narHash": "sha256-ypxFOeDz+CqADEQNL72haqGjvZQdBR5Vc7pyx2JDttI=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "755f5aa91337890c432639c60b6064bb7fe67769", + "type": "github" + } +} +``` + +Flake builds: + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix build .#dockerImage +``` + +Both commands completed successfully. + +### Development Shell + +```bash +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix develop --command python --version +Python 3.13.12 +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix develop --command python -c 'import importlib.metadata as m; print(m.version("flask"))' +3.1.2 + +s3rap1s in ~/devops/DevOps-Core-Course/labs/lab18/app_python on lab18 λ nix develop --command pytest -q +.......... [100%] +10 passed, 1 warning in 0.12s +``` + +The dev shell replaces the Lab 1 `venv` workflow with a locked environment. Entering the shell later gives the same Python and package set as long as `flake.lock` is unchanged. + +## 7. Lab 10 Helm Values vs Nix Flakes + +In Lab 10, Helm values pinned the deployment image tag: + +```yaml +image: + repository: s3rap1s/devops-info-service + tag: "v2" + pullPolicy: IfNotPresent +``` + +That is useful for Kubernetes deployment, but it does not prove how the image was built. A tag can be rebuilt and repushed, and Helm does not lock Python, Debian packages, compilers, or PyPI dependencies inside the image. + +| Aspect | Helm values.yaml | Nix Flake | +| --- | --- | --- | +| Locks deployment configuration | Yes | Not its main purpose | +| Locks image build inputs | No | Yes | +| Locks Python version | Only indirectly through image | Yes | +| Locks transitive dependencies | No | Yes, through nixpkgs | +| Protects against tag mutation | Only if using image digest | Yes for the build output | +| Best use | Kubernetes deployment | Reproducible build and dev environment | + +The strongest practical approach is to combine both: + +1. Build the image with Nix. +2. Push it to a registry. +3. Deploy with Helm using an immutable image digest instead of a mutable tag. + + diff --git a/monitoring/docker-compose.yml b/monitoring/docker-compose.yml new file mode 100644 index 0000000000..db1a6b6ce4 --- /dev/null +++ b/monitoring/docker-compose.yml @@ -0,0 +1,166 @@ +networks: + logging: + driver: bridge + +volumes: + loki-data: + grafana-data: + prometheus-data: + app-python-data: + +services: + loki: + image: grafana/loki:3.0.0 + container_name: loki + ports: + - "3100:3100" + volumes: + - ./loki/config.yml:/etc/loki/config.yml + - loki-data:/loki + command: -config.file=/etc/loki/config.yml + networks: + - logging + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost: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:3.0.0 + container_name: promtail + 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 + restart: unless-stopped + healthcheck: + test: ["CMD", "pidof", "promtail"] + interval: 10s + timeout: 5s + retries: 5 + deploy: + resources: + limits: + cpus: '0.5' + memory: 256M + reservations: + cpus: '0.25' + memory: 128M + + grafana: + image: grafana/grafana:12.3.1 + container_name: grafana + ports: + - "3000:3000" + volumes: + - grafana-data:/var/lib/grafana + environment: + - GF_AUTH_ANONYMOUS_ENABLED=${GF_AUTH_ANONYMOUS_ENABLED:-false} + - GF_SECURITY_ADMIN_PASSWORD=${GF_SECURITY_ADMIN_PASSWORD:-admin} + - GF_METRICS_ENABLED=true + networks: + - logging + depends_on: + - loki + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "curl -f http://localhost:3000/api/health || exit 1"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + 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:ro + - prometheus-data:/prometheus + command: + - '--config.file=/etc/prometheus/prometheus.yml' + - '--storage.tsdb.path=/prometheus' + - '--storage.tsdb.retention.time=15d' + - '--storage.tsdb.retention.size=10GB' + networks: + - logging + depends_on: + - app-python + - loki + - grafana + restart: unless-stopped + 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 + + app-python: + build: + context: ../app_python + image: s3rap1s/devops-info-service:latest + container_name: app-python + user: "0:0" + command: sh -c "mkdir -p /app/data && chown -R 999:999 /app/data && python app.py" + ports: + - "5000:5000" + environment: + - DATA_DIR=/app/data + volumes: + - app-python-data:/app/data + networks: + - logging + labels: + logging: "promtail" + app: "devops-python" + restart: unless-stopped + depends_on: + - loki + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/health')"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 5s + deploy: + resources: + limits: + cpus: '0.5' + memory: 256M + reservations: + cpus: '0.25' + memory: 128M diff --git a/monitoring/docs/LAB07.md b/monitoring/docs/LAB07.md new file mode 100644 index 0000000000..74843806b0 --- /dev/null +++ b/monitoring/docs/LAB07.md @@ -0,0 +1,282 @@ +# Lab 7: Observability & Logging with Loki Stack + +## 1. Architecture + +The logging stack consists of three main components: + +- **Loki** – log aggregation system. It stores logs and indexes them with labels. +- **Promtail** – log collector that runs on each node, reads container logs, and pushes them to Loki. +- **Grafana** – visualization frontend that queries Loki and displays logs in dashboards. + +All components are deployed using Docker Compose on a single VM. The application produce structured JSON logs, which are collected by Promtail (via Docker socket) and sent to Loki. Grafana connects to Loki as a data source and provides a dashboard for log exploration. + +![Architecture Diagram](screenshots/architecture-07.png) + + +## 2. Setup Guide + +### 2.1 Prerequisites +- Docker and Docker Compose v2 installed on the target VM. +- Git repository with the `monitoring/` folder. +- Your application images pushed to Docker Hub. + +### 2.2 Directory Structure +``` +monitoring +├── docker-compose.yml +├── grafana +├── loki +│ └── config.yml +└── promtail + └── config.yml +``` + +### 2.3 Environment Variables +Create a `.env` file in the `monitoring/` directory with: +``` +GF_AUTH_ANONYMOUS_ENABLED=false +GF_SECURITY_ADMIN_PASSWORD=your_secure_password +``` +This file is excluded from Git via `.gitignore`. + +### 2.4 Deploy the Stack +```bash +cd monitoring +docker compose up -d +``` + +Verify all services are running: +```bash +docker compose ps +``` +Expected output: +``` +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +app-python s3rap1s/devops-info-service:latest "python app.py" app-python 2 hours ago Up 2 hours (healthy) 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp +grafana grafana/grafana:12.3.1 "/run.sh" grafana 2 hours ago Up 2 hours (healthy) 0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp +loki grafana/loki:3.0.0 "/usr/bin/loki -conf…" loki 2 hours ago Up 2 hours (healthy) 0.0.0.0:3100->3100/tcp, [::]:3100->3100/tcp +promtail grafana/promtail:3.0.0 "/usr/bin/promtail -…" promtail 2 hours ago Up 2 hours (healthy) +``` + +### 2.5 Configure Grafana Data Source +1. Open `http://:3000` and log in with the password from `.env`. +2. Go to **Connections → Data sources → Add data source**. +3. Choose **Loki**. +4. Set URL to `http://loki:3100`. +5. Click **Save & Test** – should show success. + + +## 3. Configuration Explanation + +### 3.1 Loki Configuration (`loki/config.yml`) +```yaml +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2020-10-24 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +storage_config: + tsdb_shipper: + active_index_directory: /loki/tsdb-index + cache_location: /loki/tsdb-cache + filesystem: + directory: /loki/chunks + +limits_config: + retention_period: 168h + retention_stream: true + max_query_lookback: 168h + +compactor: + working_directory: /loki/compactor + shared_store: filesystem + compaction_interval: 10m + retention_enabled: true +``` + +**Key points:** +- `schema_config` uses **TSDB** (time-series database) with schema v13 – the recommended high‑performance storage for Loki 3.0+. +- `limits_config.retention_period: 168h` – logs are kept for 7 days. +- `compactor` enabled to periodically clean up old data. + +### 3.2 Promtail Configuration (`promtail/config.yml`) +```yaml +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +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 + filters: + - name: label + values: ["logging=promtail"] + relabel_configs: + - source_labels: ['__meta_docker_container_name'] + regex: '/(.*)' + target_label: 'container' + - source_labels: ['__meta_docker_container_label_app'] + target_label: 'app' + - source_labels: ['__meta_docker_container_label_logging'] + target_label: 'logging' +``` + +**Explanation:** +- Promtail discovers Docker containers via the Docker socket. +- `filters` ensure only containers with the label `logging=promtail` are scraped – prevents collecting logs from unrelated containers. +- `relabel_configs` extract container name and custom labels (`app`, `logging`) as Loki labels for efficient querying. + + +## 4. Application Logging + +### 4.1 Python Application JSON Logging +The Python Flask app was modified to output structured JSON logs using `python-json-logger`. +**Why JSON?** +JSON logs are easily parsable by Loki, allowing field extraction (`| json`) and filtering by log level, method, etc. + +### 4.2 Container Labels +Python application was added to `docker-compose.yml` with labels: +```yaml +labels: + logging: "promtail" + app: "devops-python" +``` +This ensures Promtail picks them up and attaches the `app` label to every log line. + + +## 5. Dashboard + +A Grafana dashboard was created with four panels, each using LogQL queries. + +### 5.1 Panel 1: All Logs (Logs Table) +- **Query:** `{app=~"devops-.*"}` +- **Visualization:** Logs +- **Purpose:** Real‑time view of all logs from both Python and Go apps. + +### 5.2 Panel 2: Request Rate (Time Series) +- **Query:** `sum by (app) (rate({app=~"devops-.*"}[1m]))` +- **Visualization:** Time series +- **Purpose:** Show requests per second per application. + +### 5.3 Panel 3: Error Logs (Logs Table) +- **Query:** `{app=~"devops-.*"} | json | level="ERROR"` +- **Visualization:** Logs +- **Purpose:** Display only error-level logs for quick troubleshooting. + +### 5.4 Panel 4: Log Level Distribution (Pie Chart) +- **Query:** `sum by (level) (count_over_time({app=~"devops-.*"} | json [5m]))` +- **Visualization:** Pie chart +- **Purpose:** Show proportion of log levels (INFO, ERROR, etc.) over the last 5 minutes. + +![Dashboard Screenshot](screenshots/dashboard.png) + +**Example LogQL explanation:** +`{app=~"devops-.*"} | json | level="ERROR"` – selects logs from both apps, parses JSON, and filters to those with `level` field equal to "ERROR". + + +## 6. Production Configuration + +### 6.1 Security +- Anonymous access disabled (`GF_AUTH_ANONYMOUS_ENABLED=false`). +- Admin password stored in `.env` file (excluded from Git). +- Grafana only accessible on port 3000 (no default credentials in code). + +### 6.2 Resource Limits +Each service has CPU and memory limits defined in the Compose file to prevent resource starvation: +```yaml +deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + reservations: + cpus: '0.5' + memory: 512M +``` + +### 6.3 Health Checks +All services include `healthcheck` directives to ensure proper operation: +- Loki: `curl -f http://localhost:3100/ready` +- Promtail: `pidof promtail` +- Grafana: `curl -f http://localhost:3000/api/health` + +### 6.4 Log Retention +Loki is configured to retain logs for 7 days (168h) via `limits_config.retention_period`. + +![Grafana login page](screenshots/grafana-login.png) + + +## 7. Testing + +### 7.1 Verify All Services Are Healthy +```bash +s3rap1s in ~/devops/DevOps-Core-Course/monitoring on lab06 ● ● λ docker compose ps +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +app-python s3rap1s/devops-info-service:latest "python app.py" app-python 2 hours ago Up 2 hours (healthy) 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp +grafana grafana/grafana:12.3.1 "/run.sh" grafana 2 hours ago Up 2 hours (healthy) 0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp +loki grafana/loki:3.0.0 "/usr/bin/loki -conf…" loki 2 hours ago Up 2 hours (healthy) 0.0.0.0:3100->3100/tcp, [::]:3100->3100/tcp +promtail grafana/promtail:3.0.0 "/usr/bin/promtail -…" promtail 2 hours ago Up 2 hours (healthy) +``` + +### 7.2 Generate Logs +```bash +for i in {1..20}; do curl -s http://localhost:8000/ > /dev/null; done +for i in {1..20}; do curl -s http://localhost:8000/health > /dev/null; done +``` + +### 7.3 Query Logs in Grafana Explore +![Explore Screenshot](screenshots/python-logs.png) +![Explore Screenshot](screenshots/python-error.png) +![Explore Screenshot](screenshots/python-filter.png) + +Example queries and their results: +``` +{app="devops-python"} +``` +Returns logs of devops-python app. + +``` +{app="devops-python"} |= "ERROR" +``` +Returns logs with only errors. + +``` +{app="devops-python"} | json | method="GET" +``` +Return logs with HTTP method GET + + +## 8. Challenges & Solutions + +### Promtail health check failing +**Problem:** Promtail image did not contain `wget`, causing the healthcheck to fail. +**Solution:** Replaced `wget` with `pidof promtail` to check that the process is running. \ No newline at end of file diff --git a/monitoring/docs/LAB08.md b/monitoring/docs/LAB08.md new file mode 100644 index 0000000000..eb119e9915 --- /dev/null +++ b/monitoring/docs/LAB08.md @@ -0,0 +1,329 @@ +# Lab 8: Metrics & Monitoring with Prometheus + +## 1. Architecture + +![Architecture Diagram](screenshots/architecture-08.png) + + +## 2. Application Instrumentation + +The Python Flask application was instrumented with `prometheus_client` and now exposes metrics on `/metrics`. + +### 2.1 Added Metrics + +- `http_requests_total{method, endpoint, status_code}` + Counts total HTTP requests. This is used to measure request rate and error counts. + +- `http_request_duration_seconds{method, endpoint, status_code}` + Histogram that records request latency. This is used for p95 latency and heatmap visualizations. + +- `http_requests_in_progress{method, endpoint}` + Tracks currently active requests. This is useful for concurrency monitoring. + +- `devops_info_endpoint_calls_total{endpoint}` + Tracks endpoint usage as an application-level metric. + +- `devops_info_system_info_collection_seconds` + Measures time spent collecting system information for the main endpoint. + +### 2.2 Why These Metrics Were Chosen + +The metric set follows the **RED method**: + +- **Rate**: `http_requests_total` +- **Errors**: `http_requests_total` filtered by `status_code` +- **Duration**: `http_request_duration_seconds` + +Additional business metrics were added to go beyond raw HTTP traffic and capture endpoint usage and internal work duration. + +### 2.3 Label Strategy + +To avoid high-cardinality metrics, labels were limited to: + +- `method` +- `endpoint` +- `status_code` + +The `endpoint` label is normalized using Flask route rules. Unknown routes are grouped into `unmatched`. + +### 2.4 Evidence + +Metrics endpoint screenshot: + +![Metrics Endpoint](screenshots/metrics.png) + +## 3. Prometheus Configuration + +Prometheus was added to `monitoring/docker-compose.yml` and configured with `monitoring/prometheus/prometheus.yml`. + +### 3.1 Scrape Targets + +Configured jobs: + +- `prometheus` -> `localhost:9090` +- `app` -> `app-python:5000/metrics` +- `loki` -> `loki:3100/metrics` +- `grafana` -> `grafana:3000/metrics` + +### 3.2 Scrape Intervals + +Global configuration: + +- `scrape_interval: 15s` +- `evaluation_interval: 15s` + +This interval is frequent enough for near-real-time monitoring without being too aggressive. + +### 3.3 Retention + +Prometheus retention is configured through startup arguments: + +- `--storage.tsdb.retention.time=15d` +- `--storage.tsdb.retention.size=10GB` + +This means Prometheus keeps metrics for up to 15 days or until the TSDB reaches 10 GB. + +### 3.4 Evidence + +Prometheus UI screenshot: + +![Prometheus UI](screenshots/prometheus.png) + +Prometheus query evidence: + +![Prometheus Query](screenshots/prometheus-query.png) + +## 4. Dashboard Walkthrough + +Grafana was configured with Prometheus as a data source, and a custom metrics dashboard was created. + +Dashboard screenshots: + +![Imported Prometheus Dashboard](screenshots/imported-dashboard-prometheus.png) + +![Prometheus Metrics Dashboard](screenshots/dashboard-prometheus.png) + +Exported dashboard JSON files: + +- `monitoring/docs/exported-dashboard.json` +- `monitoring/grafana/dashboards/devops-app-metrics.json` + +### 4.1 Panel 1: Status Code Distribution + +- **Purpose**: compare successful and failed responses +- **Query**: + +```promql +sum by (status_code) (rate(http_requests_total[5m])) +``` + +### 4.2 Panel 2: Application Uptime + +- **Purpose**: show whether the app target is up +- **Query**: + +```promql +up{job="app"} +``` + +### 4.3 Panel 3: Active Requests + +- **Purpose**: show the number of in-progress requests +- **Query**: + +```promql +sum(http_requests_in_progress) +``` + +### 4.4 Panel 4: Request Graph + +- **Purpose**: show requests per second for each endpoint +- **Query**: + +```promql +sum(rate(http_requests_total[5m])) by (endpoint) +``` + +### 4.5 Panel 5: Request Duration Heatmap + +- **Purpose**: show request latency distribution +- **Query**: + +```promql +sum(rate(http_request_duration_seconds_bucket[5m])) by (le) +``` + +### 4.6 Panel 6: Request Duration p95 + +- **Purpose**: show 95th percentile latency by endpoint +- **Query**: + +```promql +histogram_quantile(0.95, sum by (le, endpoint) (rate(http_request_duration_seconds_bucket[5m]))) +``` + +### 4.7 Additional Panel: Error Rate + +- **Purpose**: show how many 5xx errors occur over time +- **Query**: + +```promql +sum(rate(http_requests_total{status_code=~"5.."}[5m])) +``` + +## 5. PromQL Examples + +Below are example PromQL queries used during testing and dashboard creation. + +### 5.1 Check All Targets + +```promql +up +``` + +Shows whether each scrape target is reachable. A value of `1` means healthy, `0` means down. + +### 5.2 Request Rate by Endpoint + +```promql +sum by (endpoint) (rate(http_requests_total[5m])) +``` + +Calculates requests per second for each endpoint over the last 5 minutes. + +### 5.3 Error Rate + +```promql +sum(rate(http_requests_total{status_code=~"5.."}[5m])) +``` + +Shows the rate of server-side errors only. + +### 5.4 Status Code Breakdown + +```promql +sum by (status_code) (rate(http_requests_total[5m])) +``` + +Groups request rate by HTTP status code. + +### 5.5 p95 Latency + +```promql +histogram_quantile(0.95, sum by (le, endpoint) (rate(http_request_duration_seconds_bucket[5m]))) +``` + +Calculates the 95th percentile request duration from the histogram buckets. + +### 5.6 Active Requests + +```promql +sum(http_requests_in_progress) +``` + +Shows the number of requests currently being processed. + +### 5.7 Business Metric: Endpoint Calls + +```promql +sum by (endpoint) (rate(devops_info_endpoint_calls_total[5m])) +``` + +Shows which application endpoint is used most often. + +## 6. Production Setup + +### 6.1 Health Checks + +Health checks were configured for: + +- `loki` +- `promtail` +- `grafana` +- `prometheus` +- `app-python` + +This ensures service readiness is visible in `docker compose ps`. + +### 6.2 Resource Limits + +Resource limits configured in `docker-compose.yml`: + +- **Prometheus**: `1 CPU`, `1G` +- **Loki**: `1 CPU`, `1G` +- **Grafana**: `0.5 CPU`, `512M` +- **App**: `0.5 CPU`, `256M` +- **Promtail**: `0.5 CPU`, `256M` + +These limits prevent the monitoring stack from consuming excessive CPU or memory. + +### 6.3 Retention Policies + +**Prometheus** + +- `--storage.tsdb.retention.time=15d` +- `--storage.tsdb.retention.size=10GB` + +Metrics are retained for up to 15 days or 10 GB. + +**Loki** + +- `retention_period: 168h` + +Logs are retained for 7 days. + +### 6.4 Persistent Volumes + +Persistent Docker volumes: + +- `prometheus-data` +- `loki-data` +- `grafana-data` + +These volumes preserve monitoring data across container restarts. + +## 7. Testing Results + +### 7.1 Metrics Endpoint + +The application metrics endpoint returned Prometheus-formatted metrics: + +![Metrics Endpoint](screenshots/metrics.png) + +### 7.2 Prometheus Working + +Prometheus loaded successfully and queries worked: + +![Prometheus UI](screenshots/prometheus.png) + +![Prometheus Query](screenshots/prometheus-query.png) + +### 7.3 Grafana Dashboard Working + +Grafana successfully displayed Prometheus data: + +![Prometheus Dashboard](screenshots/dashboard-prometheus.png) + +### 7.4 Services Healthy + +Docker Compose showed the services running: + +![Docker Compose PS](screenshots/docker-compose-ps.png) + +### 7.5 Data Persistence After Restart + +After restarting the monitoring stack, the saved dashboard was still present: + +![Dashboard After Restart](screenshots/dashboard-after-restart.png) + +This confirms Grafana persistence via the `grafana-data` volume. + +## 8. Challenges & Solutions + +### Prometheus Not Reachable on Port 9090 + +**Problem** +Prometheus and `app-python` were created but not fully started, so `localhost:9090` was not accessible. + +**Solution** +The stopped services were started explicitly and their status was verified with `docker compose ps`. diff --git a/monitoring/docs/exported-dashboard.json b/monitoring/docs/exported-dashboard.json new file mode 100644 index 0000000000..c329c5bd9b --- /dev/null +++ b/monitoring/docs/exported-dashboard.json @@ -0,0 +1,494 @@ +{ + "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, + "id": 0, + "links": [], + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "bfgdqzed2054wf" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + } + }, + "mappings": [] + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + }, + "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": [ + { + "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": "bfgdqzed2054wf" + }, + "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": 0 + }, + "id": 2, + "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": [ + { + "editorMode": "code", + "expr": "up{job=\"app\"}", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Uptime", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "bfgdqzed2054wf" + }, + "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": 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": [ + { + "editorMode": "code", + "expr": "http_requests_in_progress", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Active requests", + "type": "gauge" + }, + { + "datasource": { + "type": "prometheus", + "uid": "bfgdqzed2054wf" + }, + "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": 8 + }, + "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": "bfgdqzed2054wf" + }, + "editorMode": "code", + "expr": "sum(rate(http_requests_total[5m])) by (endpoint)", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Request graph", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "bfgdqzed2054wf" + }, + "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": [ + { + "editorMode": "code", + "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "Request Duration Heatmap", + "type": "heatmap" + }, + { + "datasource": { + "type": "prometheus", + "uid": "bfgdqzed2054wf" + }, + "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": [ + { + "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" + } + ], + "preload": false, + "schemaVersion": 42, + "tags": [], + "templating": { + "list": [] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "New dashboard", + "uid": "adf4r5m", + "version": 16 +} \ No newline at end of file diff --git a/monitoring/docs/screenshots/architecture-07.png b/monitoring/docs/screenshots/architecture-07.png new file mode 100644 index 0000000000..dd675824ce Binary files /dev/null and b/monitoring/docs/screenshots/architecture-07.png differ diff --git a/monitoring/docs/screenshots/architecture-08.png b/monitoring/docs/screenshots/architecture-08.png new file mode 100644 index 0000000000..4da80305b4 Binary files /dev/null and b/monitoring/docs/screenshots/architecture-08.png differ diff --git a/monitoring/docs/screenshots/dashboard-after-restart.png b/monitoring/docs/screenshots/dashboard-after-restart.png new file mode 100644 index 0000000000..af2f6294c6 Binary files /dev/null and b/monitoring/docs/screenshots/dashboard-after-restart.png differ diff --git a/monitoring/docs/screenshots/dashboard-prometheus.png b/monitoring/docs/screenshots/dashboard-prometheus.png new file mode 100644 index 0000000000..d973026abb Binary files /dev/null and b/monitoring/docs/screenshots/dashboard-prometheus.png differ diff --git a/monitoring/docs/screenshots/dashboard.png b/monitoring/docs/screenshots/dashboard.png new file mode 100644 index 0000000000..2af766e9cf Binary files /dev/null and b/monitoring/docs/screenshots/dashboard.png differ diff --git a/monitoring/docs/screenshots/docker-compose-ps.png b/monitoring/docs/screenshots/docker-compose-ps.png new file mode 100644 index 0000000000..cdc15c82d6 Binary files /dev/null and b/monitoring/docs/screenshots/docker-compose-ps.png differ diff --git a/monitoring/docs/screenshots/grafana-login.png b/monitoring/docs/screenshots/grafana-login.png new file mode 100644 index 0000000000..143b2cd9a2 Binary files /dev/null and b/monitoring/docs/screenshots/grafana-login.png differ diff --git a/monitoring/docs/screenshots/imported-dashboard-prometheus.png b/monitoring/docs/screenshots/imported-dashboard-prometheus.png new file mode 100644 index 0000000000..95e892d2f6 Binary files /dev/null and b/monitoring/docs/screenshots/imported-dashboard-prometheus.png differ diff --git a/monitoring/docs/screenshots/metrics.png b/monitoring/docs/screenshots/metrics.png new file mode 100644 index 0000000000..ed2e322907 Binary files /dev/null and b/monitoring/docs/screenshots/metrics.png differ diff --git a/monitoring/docs/screenshots/prometheus-query.png b/monitoring/docs/screenshots/prometheus-query.png new file mode 100644 index 0000000000..92940ce482 Binary files /dev/null and b/monitoring/docs/screenshots/prometheus-query.png differ diff --git a/monitoring/docs/screenshots/prometheus.png b/monitoring/docs/screenshots/prometheus.png new file mode 100644 index 0000000000..62147c7804 Binary files /dev/null and b/monitoring/docs/screenshots/prometheus.png differ diff --git a/monitoring/docs/screenshots/python-error.png b/monitoring/docs/screenshots/python-error.png new file mode 100644 index 0000000000..901a3c7937 Binary files /dev/null and b/monitoring/docs/screenshots/python-error.png differ diff --git a/monitoring/docs/screenshots/python-filter.png b/monitoring/docs/screenshots/python-filter.png new file mode 100644 index 0000000000..5f22b1fa15 Binary files /dev/null and b/monitoring/docs/screenshots/python-filter.png differ diff --git a/monitoring/docs/screenshots/python-logs.png b/monitoring/docs/screenshots/python-logs.png new file mode 100644 index 0000000000..182d740354 Binary files /dev/null and b/monitoring/docs/screenshots/python-logs.png differ diff --git a/monitoring/grafana/dashboards/devops-app-metrics.json b/monitoring/grafana/dashboards/devops-app-metrics.json new file mode 100644 index 0000000000..7a96a7a5d3 --- /dev/null +++ b/monitoring/grafana/dashboards/devops-app-metrics.json @@ -0,0 +1,441 @@ +{ + "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, + "id": null, + "links": [], + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "unit": "reqps" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "editorMode": "code", + "expr": "sum by (endpoint) (rate(http_requests_total[5m]))", + "legendFormat": "{{endpoint}}", + "range": true, + "refId": "A" + } + ], + "title": "Request Rate by Endpoint", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "unit": "reqps" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 0 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "editorMode": "code", + "expr": "sum(rate(http_requests_total{status_code=~\"5..\"}[5m]))", + "legendFormat": "5xx", + "range": true, + "refId": "A" + } + ], + "title": "Error Rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 8 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum by (le, endpoint) (rate(http_request_duration_seconds_bucket[5m])))", + "legendFormat": "{{endpoint}}", + "range": true, + "refId": "A" + } + ], + "title": "Request Duration p95", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-BlYlRd" + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 8 + }, + "id": 4, + "options": { + "calculate": false, + "cellGap": 1, + "color": { + "exponent": 0.5, + "fill": "dark-orange", + "mode": "scheme", + "reverse": false, + "scale": "exponential", + "scheme": "Oranges", + "steps": 128 + }, + "filterValues": { + "le": 1e-9 + }, + "legend": { + "show": false + }, + "rowsFrame": { + "layout": "auto" + }, + "showValue": "never", + "tooltip": { + "show": true, + "yHistogram": false + }, + "yAxis": { + "axisPlacement": "left", + "reverse": false, + "unit": "s" + } + }, + "targets": [ + { + "editorMode": "code", + "expr": "sum by (le) (rate(http_request_duration_seconds_bucket[5m]))", + "format": "heatmap", + "legendFormat": "{{le}}", + "range": true, + "refId": "A" + } + ], + "title": "Request Duration Heatmap", + "type": "heatmap" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "max": 10, + "min": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 3 + }, + { + "color": "red", + "value": 6 + } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 6, + "x": 0, + "y": 16 + }, + "id": 5, + "options": { + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "showThresholdLabels": false, + "showThresholdMarkers": true + }, + "targets": [ + { + "editorMode": "code", + "expr": "sum(http_requests_in_progress)", + "refId": "A" + } + ], + "title": "Active Requests", + "type": "gauge" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "mappings": [], + "unit": "reqps" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 10, + "x": 6, + "y": 16 + }, + "id": 6, + "options": { + "displayLabels": [ + "name", + "percent" + ], + "legend": { + "displayMode": "list", + "placement": "right", + "showLegend": true + }, + "pieType": "pie", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "editorMode": "code", + "expr": "sum by (status_code) (rate(http_requests_total[5m]))", + "legendFormat": "{{status_code}}", + "refId": "A" + } + ], + "title": "Status Code Distribution", + "type": "piechart" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [ + { + "options": { + "0": { + "color": "red", + "index": 0, + "text": "Down" + }, + "1": { + "color": "green", + "index": 1, + "text": "Up" + } + }, + "type": "value" + } + ], + "max": 1, + "min": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "green", + "value": 1 + } + ] + }, + "unit": "none" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 16 + }, + "id": 7, + "options": { + "colorMode": "background", + "graphMode": "none", + "justifyMode": "center", + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "textMode": "auto" + }, + "targets": [ + { + "editorMode": "code", + "expr": "up{job=\"app\"}", + "refId": "A" + } + ], + "title": "Application Uptime", + "type": "stat" + } + ], + "refresh": "10s", + "schemaVersion": 41, + "style": "dark", + "tags": [ + "devops", + "lab08", + "prometheus" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-15m", + "to": "now" + }, + "timepicker": {}, + "timezone": "", + "title": "DevOps App Metrics", + "uid": "devops-app-metrics", + "version": 1, + "weekStart": "" +} diff --git a/monitoring/loki/config.yml b/monitoring/loki/config.yml new file mode 100644 index 0000000000..8fce7023a6 --- /dev/null +++ b/monitoring/loki/config.yml @@ -0,0 +1,45 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + instance_addr: 127.0.0.1 + kvstore: + store: inmemory + + +schema_config: + configs: + - from: 2020-10-24 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +storage_config: + tsdb_shipper: + active_index_directory: /loki/tsdb-index + cache_location: /loki/tsdb-cache + filesystem: + directory: /loki/chunks + +limits_config: + retention_period: 168h + +compactor: + working_directory: /loki/compactor + compaction_interval: 10m + retention_enabled: true + retention_delete_delay: 2h + retention_delete_worker_count: 150 + delete_request_store: filesystem \ No newline at end of file diff --git a/monitoring/prometheus/prometheus.yml b/monitoring/prometheus/prometheus.yml new file mode 100644 index 0000000000..d6b362228f --- /dev/null +++ b/monitoring/prometheus/prometheus.yml @@ -0,0 +1,27 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + +scrape_configs: + - job_name: prometheus + static_configs: + - targets: + - localhost:9090 + + - job_name: app + metrics_path: /metrics + static_configs: + - targets: + - app-python:5000 + + - job_name: loki + metrics_path: /metrics + static_configs: + - targets: + - loki:3100 + + - job_name: grafana + metrics_path: /metrics + static_configs: + - targets: + - grafana:3000 diff --git a/monitoring/promtail/config.yml b/monitoring/promtail/config.yml new file mode 100644 index 0000000000..3014f996fa --- /dev/null +++ b/monitoring/promtail/config.yml @@ -0,0 +1,26 @@ +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +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 + filters: + - name: label + values: ["logging=promtail"] + relabel_configs: + - source_labels: ['__meta_docker_container_name'] + regex: '/(.*)' + target_label: 'container' + - source_labels: ['__meta_docker_container_label_app'] + target_label: 'app' + - source_labels: ['__meta_docker_container_label_logging'] + target_label: 'logging' \ No newline at end of file