#!/bin/bash

UWSGI_UID='uwsgi'
UWSGI_GID='uwsgi'

UWSGI_BUFFER_SIZE='12288'
UWSGI_TIMEOUT='90'
UWSGI_HEADERS='Connection:Keep-Alive'

# Default cap of 30 workers. With --lazy-apps each worker independently re-imports
# the app (~100s, ~300-500MB RSS), so a high ceiling causes cgroup OOM under load.
# `pool_size=15` in analytics/config.py is the original concurrency target.
UWSGI_WORKERS="${UWSGI_WORKERS:-30}"
UWSGI_CHEAPER="${UWSGI_CHEAPER:-15}"
UWSGI_CHEAPER_ALGO="${UWSGI_CHEAPER_ALGO:-spare}"
UWSGI_CHEAPER_OVERLOAD="${UWSGI_CHEAPER_OVERLOAD:-5}"
UWSGI_CHEAPER_STEP="${UWSGI_CHEAPER_STEP:-5}"
UWSGI_CHEAPER_INITIAL="${UWSGI_CHEAPER_INITIAL:-15}"

cd /var/app

# defaulting to application.py if not explicitly set
[ -z "${WSGI_PATH}" ] && WSGI_PATH=application.py

# ddtrace is loaded via `--import=ddtrace.auto` (the modern, lazy-apps-compatible
# entry point). Do NOT additionally wrap with `ddtrace-run` — under `--lazy-apps`
# the two paths conflict and ddtrace aborts auto-instrumentation with
# `uWSGIConfigError: Unable to access uwsgi options`.
#
# Notable flags:
#   --need-app          fail loudly if the WSGI app fails to import (no zombie master)
#   --post-buffering    silences the "harakiri without post buffering" warning and
#                       lets harakiri safely kill slow uploads
#   --cheaper-overload  wait N seconds of full-load before spawning more workers
uwsgi --cache2 name=uwsgi_cache,items=10 --http :8080 --chdir /var/app --wsgi-file ${WSGI_PATH} --module application:app --master --need-app --uid ${UWSGI_UID} --gid ${UWSGI_GID} -t ${UWSGI_TIMEOUT} --http-keepalive --add-header ${UWSGI_HEADERS} --buffer-size ${UWSGI_BUFFER_SIZE} --post-buffering 65536 --enable-threads --workers ${UWSGI_WORKERS} --cheaper ${UWSGI_CHEAPER} --cheaper-algo ${UWSGI_CHEAPER_ALGO} --cheaper-initial ${UWSGI_CHEAPER_INITIAL} --cheaper-step ${UWSGI_CHEAPER_STEP} --cheaper-overload ${UWSGI_CHEAPER_OVERLOAD} --harakiri-verbose --lazy-apps --import=ddtrace.auto --py-call-uwsgi-fork-hooks
