Every command uses the variables from section 01. Run them in order in Cloud Shell. One Docker image is built once and used by five jobs and three services. CPU and memory sizes are a 💡 starting point.
export PROJECT_ID="asapify-<initials>-2026" # replace with the team project export REGION="asia-southeast2" export GEMINI_LOCATION="global" # us-central1 if the model is not available yet export GEMINI_MODEL="<latest Gemini Flash model name>" export DATA_BUCKET="asapify-data-$PROJECT_ID" # features, scores, baselines, crops export PUBLIC_BUCKET="asapify-public-$PROJECT_ID" # static map layers (peat boundary, province boundaries) export BBOX="94.9,-6.2,119.4,6.2" # Sumatra + Kalimantan, clipped by the peat mask export BACKTEST_BBOX="113.5,-2.6,114.3,-1.9" # Central Kalimantan sub-area (main) export BACKTEST_BBOX_SUMSEL="105.2,-3.7,106.0,-3.0" # OKI, South Sumatra (planned) export WARMUP_START="2023-08-01"; export BACKTEST_START="2023-09-01"; export BACKTEST_END="2023-10-15" export IMAGE="$REGION-docker.pkg.dev/$PROJECT_ID/asapify/app:latest" export TG_BOT_USERNAME="asapify_demo_bot" # bot username from Runbook S0-5 export TG_OPERATOR_CHAT_ID="-100…" # operator group chat_id, Runbook S0-5 gcloud config set project $PROJECT_ID JOBS_SA="sa-jobs@$PROJECT_ID.iam.gserviceaccount.com" AGENT_SA="sa-agent@$PROJECT_ID.iam.gserviceaccount.com" API_SA="sa-api@$PROJECT_ID.iam.gserviceaccount.com" SCHED_SA="sa-scheduler@$PROJECT_ID.iam.gserviceaccount.com" NOTIFY_SA="sa-notify@$PROJECT_ID.iam.gserviceaccount.com" TASK_SA="sa-task@$PROJECT_ID.iam.gserviceaccount.com"
gcloud services enable \ run.googleapis.com cloudscheduler.googleapis.com cloudbuild.googleapis.com \ artifactregistry.googleapis.com firestore.googleapis.com storage.googleapis.com \ secretmanager.googleapis.com aiplatform.googleapis.com earthengine.googleapis.com \ iamcredentials.googleapis.com logging.googleapis.com monitoring.googleapis.com \ firebase.googleapis.com firebasehosting.googleapis.com identitytoolkit.googleapis.com \ cloudtasks.googleapis.com fcm.googleapis.com
Only sa-agent can call Gemini and read MAP_KEY. Jobs have neither Gemini access nor the bot token. For subscriber DMs the bot token is read only by the asapify-notify worker.
| Account | Used by | Roles |
|---|---|---|
sa-jobs | ingest-himawari, ingest-gk2a, evaluate, environment, build | roles/datastore.user, roles/storage.objectAdmin (data bucket), roles/storage.objectAdmin (public bucket, for map layers), roles/earthengine.writer + roles/serviceusage.serviceUsageConsumer (build: WorldCover), roles/run.invoker on asapify-agent |
sa-agent | asapify-agent | roles/datastore.user, roles/aiplatform.user, roles/storage.objectAdmin (data bucket), roles/secretmanager.secretAccessor (FIRMS, Telegram), roles/iam.serviceAccountTokenCreator on itself (signed crop URLs) |
sa-api | asapify-api | roles/datastore.user, roles/storage.objectViewer (data bucket, reads score/), roles/secretmanager.secretAccessor (Telegram webhook secret), roles/iam.serviceAccountTokenCreator on itself (signed URLs for the UI), roles/run.invoker on asapify-agent (re-verification), roles/cloudtasks.enqueuer, roles/iam.serviceAccountUser on sa-task |
sa-scheduler | Cloud Scheduler | roles/run.invoker (runs the jobs) |
sa-notify | asapify-notify (worker) | roles/datastore.user, roles/firebasecloudmessaging.admin, roles/secretmanager.secretAccessor (bot token), roles/cloudtasks.enqueuer + roles/iam.serviceAccountUser on sa-task (sweep) |
sa-task | Cloud Tasks and the Scheduler sweep (OIDC token) | roles/run.invoker on asapify-notify only; no data access |
for SA in sa-jobs sa-agent sa-api sa-scheduler sa-notify sa-task; do gcloud iam service-accounts create $SA; done for R in roles/datastore.user roles/earthengine.writer roles/serviceusage.serviceUsageConsumer; do gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$JOBS_SA" --role $R; done for R in roles/datastore.user roles/aiplatform.user; do gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$AGENT_SA" --role $R; done gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$API_SA" --role roles/datastore.user gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$SCHED_SA" --role roles/run.invoker for R in roles/datastore.user roles/firebasecloudmessaging.admin roles/cloudtasks.enqueuer; do gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$NOTIFY_SA" --role $R; done gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:$API_SA" --role roles/cloudtasks.enqueuer # api and worker create tasks as sa-task (OIDC token to the worker) for SA in $API_SA $NOTIFY_SA; do gcloud iam service-accounts add-iam-policy-binding $TASK_SA \ --member "serviceAccount:$SA" --role roles/iam.serviceAccountUser; done # signed URLs: each service signs as itself for SA in $AGENT_SA $API_SA; do gcloud iam service-accounts add-iam-policy-binding $SA \ --member "serviceAccount:$SA" --role roles/iam.serviceAccountTokenCreator; done # run.invoker on asapify-agent and asapify-notify is granted after the services exist (section 09)
# created in Runbook S0-4 and S0-5; this only grants access gcloud secrets add-iam-policy-binding firms-map-key \ --member "serviceAccount:$AGENT_SA" --role roles/secretmanager.secretAccessor for M in $AGENT_SA $NOTIFY_SA; do gcloud secrets add-iam-policy-binding telegram-bot-token \ --member "serviceAccount:$M" --role roles/secretmanager.secretAccessor; done # webhook secret: random, read only by api to check the header from Telegram openssl rand -hex 32 | gcloud secrets create telegram-webhook-secret --data-file=- gcloud secrets add-iam-policy-binding telegram-webhook-secret \ --member "serviceAccount:$API_SA" --role roles/secretmanager.secretAccessor
The backtest that uses FIRMS SP runs from a team member's laptop with MAP_KEY in a local environment variable, not from a job. Jobs never read MAP_KEY.
for B in $DATA_BUCKET $PUBLIC_BUCKET; do
gcloud storage buckets create gs://$B --location=$REGION \
--uniform-bucket-level-access
done
gcloud storage buckets add-iam-policy-binding gs://$PUBLIC_BUCKET \
--member=allUsers --role=roles/storage.objectViewer
for SA in $JOBS_SA $AGENT_SA; do
gcloud storage buckets add-iam-policy-binding gs://$DATA_BUCKET \
--member="serviceAccount:$SA" --role=roles/storage.objectAdmin; done
gcloud storage buckets add-iam-policy-binding gs://$PUBLIC_BUCKET \
--member="serviceAccount:$JOBS_SA" --role=roles/storage.objectAdmin
gcloud storage buckets add-iam-policy-binding gs://$DATA_BUCKET \
--member="serviceAccount:$API_SA" --role=roles/storage.objectViewer
gcloud storage buckets update gs://$DATA_BUCKET --lifecycle-file=infra/lifecycle.json
{ "rule": [{ "action": { "type": "Delete" },
"condition": { "age": 150,
"matchesPrefix": ["himawari/", "gk2a/", "score/", "raw/firms/"] } }] }
gcloud firestore databases create --location=$REGION --type=firestore-native
# firestore.rules: allow read, write: if false;
firebase deploy --only firestore:rules,firestore:indexes
The 150-day age counts from object creation, so backtest data backfilled in early October survives until the final on 4 December. peat/ and environment/ are never deleted.
# the browser reads the public bucket from the web domain, so it needs CORS cat > infra/cors.json <<'EOF' [{"origin": ["https://<PROJECT_ID>.web.app", "http://localhost:5173"], "method": ["GET"], "responseHeader": ["Content-Type"], "maxAgeSeconds": 3600}] EOF gcloud storage buckets update gs://$PUBLIC_BUCKET --cors-file=infra/cors.json # 15 provinces, simplified to ±90 KB for the map (original: data/ref/provinces.geojson) python - <<'EOF' import geopandas as gpd g = gpd.read_file("data/ref/provinces.geojson").rename(columns={"shapeName": "name"}) g["geometry"] = g.geometry.simplify(0.01, preserve_topology=True) g[["code", "name", "geometry"]].to_file("data/ref/provinces_web.geojson", driver="GeoJSON") EOF gcloud storage cp data/ref/provinces_web.geojson gs://$PUBLIC_BUCKET/layers/provinces.geojson # layers/peat_pixels.geojson is written by asapify-build (A1)
The NOAA buckets are read anonymously, with no AWS account and no cost; they are a download archive, not our infrastructure. In submission material call it "NOAA open data".
| Source | Address | Used by | Notes |
|---|---|---|---|
| Himawari-9 | s3://noaa-himawari9/AHI-L1b-FLDK/YYYY/MM/DD/HHMM/ | ingest-himawari, tool fetch_himawari_image | B07 + B14, segments S05/S06 ⚠️; .DAT.bz2 |
| GK2A | s3://noaa-gk2a-pds/AMI/L1B/FD/YYYYMM/DD/HH/ | ingest-gk2a | gk2a_ami_le1b_{sw038,ir105}_fd020ge_YYYYMMDDHHMM.nc, ~30 MB/channel; archive starts 16 Feb 2023 |
| NASA POWER | https://power.larc.nasa.gov/api/temporal/hourly/point | environment | parameters=TS,T2M, time-standard=UTC; ~1.5 day latency; 0.2 s pause between requests |
| NASA FIRMS | https://firms.modaps.eosdis.nasa.gov/api/area/csv/… | tool get_latest_viirs (agent) | MAP_KEY; ≤ 5 days per request; 5,000 transactions/10 min |
| NASA GIBS | https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi | tool fetch_viirs_image (agent) | WMS 1.3.0; BBOX=lat_min,lon_min,lat_max,lon_max |
| KHG BIG | REST …/SUMBER_DAYA_ALAM_DAN_LINGKUNGAN/MapServer/37 | build | 1,000 features per request |
Outbound traffic from Cloud Run uses default egress; no NAT needed. A GK2A full-disk download is ~60 MB per slot: do not run a large backfill from a laptop.
sa-jobs already has earthengine.writer and Service Usage Consumer (section 03).asapify-build (ESA/WorldCover/v200, class 50). No Landsat, no calls from the agent.sa-agentTrue$GEMINI_LOCATIONasapify-agent, only for AWAS clustersFROM python:3.12-slim WORKDIR /app COPY requirements.lock . RUN pip install --no-cache-dir -r requirements.lock COPY shared/ shared/ COPY jobs/ jobs/ COPY agent/ agent/ COPY api/ api/ ENV PYTHONUNBUFFERED=1
.venv/ data/local/ web/ notebooks/ docs/ .git/
gcloud artifacts repositories create asapify --repository-format=docker --location=$REGION gcloud builds submit --tag $IMAGE . # repeat after every code change # 1) asapify-agent: private, callable only by sa-jobs and sa-api gcloud run deploy asapify-agent --image $IMAGE --region $REGION \ --command uvicorn --args=agent.main:app,--host,0.0.0.0,--port,8080 \ --service-account $AGENT_SA --no-allow-unauthenticated \ --cpu 1 --memory 2Gi --concurrency 4 --min-instances 0 --max-instances 3 --timeout 300 \ --set-env-vars "GOOGLE_CLOUD_PROJECT=$PROJECT_ID,GOOGLE_CLOUD_LOCATION=$GEMINI_LOCATION,\ GOOGLE_GENAI_USE_VERTEXAI=True,GEMINI_MODEL=$GEMINI_MODEL,DATA_BUCKET=$DATA_BUCKET,\ TELEGRAM_OPERATOR_CHAT_ID=$TG_OPERATOR_CHAT_ID" \ --set-secrets FIRMS_MAP_KEY=firms-map-key:latest,TELEGRAM_BOT_TOKEN=telegram-bot-token:latest for SA in $JOBS_SA $API_SA; do gcloud run services add-iam-policy-binding asapify-agent --region $REGION \ --member "serviceAccount:$SA" --role roles/run.invoker; done AGENT_URL=$(gcloud run services describe asapify-agent --region $REGION --format='value(status.url)') # 2) asapify-api: public for the web app; operator endpoints guarded by a Firebase token in code gcloud run deploy asapify-api --image $IMAGE --region $REGION \ --command uvicorn --args=api.main:app,--host,0.0.0.0,--port,8080 \ --service-account $API_SA --allow-unauthenticated \ --cpu 1 --memory 1Gi --concurrency 40 --min-instances 0 --max-instances 3 --timeout 60 \ --set-env-vars "GOOGLE_CLOUD_PROJECT=$PROJECT_ID,DATA_BUCKET=$DATA_BUCKET,AGENT_URL=$AGENT_URL,\ TELEGRAM_BOT_USERNAME=$TG_BOT_USERNAME,NOTIFICATION_MODE=dry_run" \ --set-secrets TELEGRAM_WEBHOOK_SECRET=telegram-webhook-secret:latest # 3) asapify-notify: private worker, same image and code as api; only sa-task may call it gcloud run deploy asapify-notify --image $IMAGE --region $REGION \ --command uvicorn --args=api.main:app,--host,0.0.0.0,--port,8080 \ --service-account $NOTIFY_SA --no-allow-unauthenticated \ --cpu 1 --memory 512Mi --concurrency 4 --min-instances 0 --max-instances 2 --timeout 60 \ --set-env-vars "GOOGLE_CLOUD_PROJECT=$PROJECT_ID,NOTIFICATION_MODE=dry_run,TELEGRAM_ENABLED=false,\ FCM_ENABLED=false,ASAPIFY_PUBLIC_ORIGIN=https://$PROJECT_ID.web.app" \ --set-secrets TELEGRAM_BOT_TOKEN=telegram-bot-token:latest gcloud run services add-iam-policy-binding asapify-notify --region $REGION \ --member "serviceAccount:$TASK_SA" --role roles/run.invoker NOTIFY_URL=$(gcloud run services describe asapify-notify --region $REGION --format='value(status.url)') # Cloud Tasks queue and a sweep every minute; api and worker need the worker URL as the OIDC audience gcloud tasks queues create asapify-notifications --location $REGION \ --max-dispatches-per-second 5 --max-concurrent-dispatches 2 --max-attempts 8 \ --min-backoff 10s --max-backoff 300s --max-retry-duration 3600s for S in asapify-api asapify-notify; do gcloud run services update $S --region $REGION \ --update-env-vars "NOTIFICATION_WORKER_URL=$NOTIFY_URL,NOTIFICATION_TASK_CALLER=$TASK_SA"; done gcloud scheduler jobs create http asapify-notification-recovery --location $REGION \ --schedule "* * * * *" --time-zone "Asia/Jakarta" --http-method POST \ --uri "$NOTIFY_URL/_internal/notifications/sweep" \ --oidc-service-account-email $TASK_SA --oidc-token-audience $NOTIFY_URL # Telegram webhook to link accounts (/start); run it once Hosting is live (section 11) curl -s "https://api.telegram.org/bot$(gcloud secrets versions access latest --secret telegram-bot-token)/setWebhook" \ -d url="https://$PROJECT_ID.web.app/api/v1/notifications/telegram-webhook" \ -d secret_token="$(gcloud secrets versions access latest --secret telegram-webhook-secret)" \ -d allowed_updates='["message"]'
⚠️ If gcloud builds submit fails because of Cloud Build service account permissions in a new project, give the build account roles/artifactregistry.writer and roles/logging.logWriter, then retry. ⚠️ If a requirements.lock made on Mac/Windows fails to install on Linux, regenerate the lock in Cloud Shell. Judging day: --min-instances 1 for asapify-agent and asapify-api.
The API and Notification Engine code already lives in the team repo ktp-asapify-be, with python3 gcp/manage.py … and python3 -m gcp.notifications … scripts (without --apply they only print the plan; they name accounts asapify-*). The default mode is dry_run: nothing is sent until NOTIFICATION_MODE=live and TELEGRAM_ENABLED=true are set on api and the worker, after a test with a demo subscriber account.
ENV="GOOGLE_CLOUD_PROJECT=$PROJECT_ID,DATA_BUCKET=$DATA_BUCKET,PUBLIC_BUCKET=$PUBLIC_BUCKET,BBOX=$BBOX,AGENT_URL=$AGENT_URL"
COMMON="--image $IMAGE --region $REGION --service-account $JOBS_SA --command python --set-env-vars $ENV"
gcloud run jobs deploy asapify-ingest-himawari $COMMON --args=-m,jobs.ingest,--sat,himawari \
--cpu 2 --memory 4Gi --task-timeout 8m --max-retries 0
gcloud run jobs deploy asapify-ingest-gk2a $COMMON --args=-m,jobs.ingest,--sat,gk2a \
--cpu 2 --memory 4Gi --task-timeout 8m --max-retries 0
gcloud run jobs deploy asapify-evaluate $COMMON --args=-m,jobs.evaluate \
--cpu 2 --memory 4Gi --task-timeout 8m --max-retries 0
gcloud run jobs deploy asapify-environment $COMMON --args=-m,jobs.environment \
--cpu 2 --memory 4Gi --task-timeout 30m --max-retries 1
gcloud run jobs deploy asapify-build $COMMON --args=-m,jobs.build_all \
--cpu 2 --memory 8Gi --task-timeout 60m --max-retries 0
for JOB in "asapify-ingest-himawari|*/10 20-23,0-4 * * *" \
"asapify-ingest-gk2a|*/10 20-23,0-4 * * *" \
"asapify-evaluate|5-59/10 20-23,0-4 * * *" \
"asapify-environment|0 12 * * *"; do
NAME="${JOB%%|*}"; CRON="${JOB#*|}"
gcloud scheduler jobs create http "$NAME-schedule" --location $REGION \
--schedule "$CRON" --time-zone "Asia/Jakarta" \
--uri "https://run.googleapis.com/v2/projects/$PROJECT_ID/locations/$REGION/jobs/$NAME:run" \
--http-method POST --oauth-service-account-email $SCHED_SA
done
# once after deploy
gcloud run jobs execute asapify-build --region $REGION --wait
# replay one slot (AS_OF replaces the current time)
gcloud run jobs execute asapify-ingest-gk2a --region $REGION --wait \
--update-env-vars AS_OF=2023-09-25T15:00:00Z
# parallel backfill: 8 tasks, each takes dates by CLOUD_RUN_TASK_INDEX
gcloud run jobs execute asapify-ingest-gk2a --region $REGION --tasks 8 --task-timeout 6h \
--args=-m,jobs.backfill,--sat,gk2a,--start,$BACKTEST_START,--end,$BACKTEST_END,--step,10,--night-only
The 20-23,0-4 WIB schedule covers 20:00–04:50; slots after 04:00 WIB (21:00 UTC) are skipped in code. Ingest and evaluate have no retries because the next cycle is 10 minutes away and everything is idempotent per slot. Evaluate runs 5 minutes after ingest so files from both satellites have time to land.
The web app lives in the team repo ktp-asapify-fe, including the firebase.json below. The judged prototype URL must be on Firebase Hosting or Cloud Run (competition rule); the mock-mode preview on Vercel is for internal review only.
{ "hosting": { "public": "dist", "rewrites": [
{ "source": "/api/**",
"run": { "serviceId": "asapify-api", "region": "asia-southeast2" } },
{ "source": "**", "destination": "/index.html" } ],
"headers": [
{ "source": "/maplibre/**", # map worker = JS module
"headers": [{ "key": "Content-Type", "value": "text/javascript" }] },
{ "source": "/notification-sw.js", # push + offline service worker
"headers": [{ "key": "Cache-Control", "value": "no-cache" }] } ] } }
import sys, firebase_admin
from firebase_admin import auth
firebase_admin.initialize_app()
email, role = sys.argv[1], sys.argv[2] # operator
auth.set_custom_user_claims(
auth.get_user_by_email(email).uid, {"role": role})
VITE_API_MODE=live VITE_API_BASE= # empty = same-origin /api through the Hosting rewrite VITE_PEAT_LAYER_URL=https://storage.googleapis.com/<PUBLIC_BUCKET>/layers/peat_pixels.geojson VITE_PROVINCES_LAYER_URL=https://storage.googleapis.com/<PUBLIC_BUCKET>/layers/provinces.geojson VITE_FIREBASE_API_KEY=<Firebase Web App> # public web config, not an admin key VITE_FIREBASE_AUTH_DOMAIN=<PROJECT_ID>.firebaseapp.com VITE_FIREBASE_PROJECT_ID=<PROJECT_ID> VITE_FIREBASE_APP_ID=<Firebase Web App> VITE_FIREBASE_MESSAGING_SENDER_ID=<Firebase> # exercise push (optional) VITE_FIREBASE_VAPID_KEY=<Web Push certificate> # VITE_* variables are read at build time npm ci && npm run build && firebase deploy --only hosting
asia-southeast2. If it does not, set VITE_API_BASE to the asapify-api URL and allow the web origin through CORS in the API. asapify-agent is never called from the browser.| What is watched | When it alerts |
|---|---|
Successful ingest per satellite (log run_success, label sat) | none for 30 minutes during night hours |
Latency per satellite (log scan_latency_min) | median > 30 minutes over 2 hours |
Evaluate with one satellite (log n_sat) | n_sat = 1 on > 50% of slots over 2 hours |
Environment (log power_cells_ok) | < 90% of POWER cells succeed |
| Agent verification fails | > 2 times in a row |
Uptime of /api/v1/health | 2 failures in a row |
Notification jobs failed / unknown (collection notification_jobs) | > 0 within 15 minutes |
Alerts with fanout = pending | for more than 5 minutes (the sweep is not running or fan-out keeps failing) |
| Cost | 50%, 90%, 100% of the team budget |
| Variable | agent | api | notify | job (all) |
|---|---|---|---|---|
GOOGLE_CLOUD_PROJECT, DATA_BUCKET | ✓ | ✓ | ✓ (project only) | ✓ |
GOOGLE_CLOUD_LOCATION, GOOGLE_GENAI_USE_VERTEXAI, GEMINI_MODEL | ✓ | |||
PUBLIC_BUCKET, BBOX | ✓ | |||
AGENT_URL | ✓ | ✓ (evaluate) | ||
AS_OF (optional, replay) | ✓ | |||
FIRMS_MAP_KEY (secret) | ✓ | |||
TELEGRAM_BOT_TOKEN (secret) | ✓ | ✓ | ||
TELEGRAM_OPERATOR_CHAT_ID | ✓ | |||
TELEGRAM_WEBHOOK_SECRET (secret), TELEGRAM_BOT_USERNAME | ✓ | |||
NOTIFICATION_MODE, TELEGRAM_ENABLED, FCM_ENABLED | ✓ | ✓ | ||
NOTIFICATION_WORKER_URL, NOTIFICATION_TASK_CALLER | ✓ | ✓ | ||
ASAPIFY_PUBLIC_ORIGIN | ✓ |
The web app (ktp-asapify-fe) uses none of the variables above; it is built with VITE_API_MODE, VITE_API_BASE, VITE_PEAT_LAYER_URL, VITE_PROVINCES_LAYER_URL and VITE_FIREBASE_* (section 11).
env.sh, enable APIs, register Earth Engine (Runbook S0-2, S0-3).ktp-asapify-be/gcp/firestore.indexes.json.asapify-agent, asapify-api, then asapify-notify with its queue and sweep (09); check /api/v1/health.asapify-build once.asapify-environment --as-of for each day of the backtest window.ktp-asapify-fe in live mode and deploy to Firebase Hosting (11); enable Auth, set up the demo operator account; set the Telegram webhook (09).dry_run, then set NOTIFICATION_MODE=live and TELEGRAM_ENABLED=true on api and the worker.