# The function runner's execution core.
#
# This directory builds two ways: as a subdirectory of the root project, and as
# a project of its own (`cmake -S runner -B build-runner`). The second is how it
# gets built and tested on the dev host, where the root project cannot configure
# at all because smartbotic-db-client is unbuildable there (see CLAUDE.md).
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
    cmake_minimum_required(VERSION 3.20)
    project(smartbotic-vectorapi-runner LANGUAGES C CXX)
    set(CMAKE_CXX_STANDARD 20)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)
    if(NOT CMAKE_BUILD_TYPE)
        set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type" FORCE)
    endif()
    option(BUILD_TESTS "Build tests" ON)
    enable_testing()
endif()

# QuickJS is C, and the root project declares CXX only.
enable_language(C)

#
# Deliberately self-contained: it links neither vectorapi_core nor
# smartbotic-db-client, so it configures, builds and tests on the dev host whose
# protobuf is too new for the database client (see CLAUDE.md gotchas). The
# host-binding workstream that does need the gateway links THAT on top of this
# target, it does not move the dependency in here.

include(FetchContent)

# quickjs-ng rather than Bellard's quickjs: it ships a real CMake build, exports
# the module/promise/bytecode entry points we need as public API
# (JS_GetModuleNamespace, JS_PromiseState, JS_SetMaxStackSize), builds clean
# under a C++ TU's expectations, and is the variant that is actually maintained.
# Pinned to an exact tag - bytecode has no version stamp, so a silent QuickJS
# upgrade would make cached blobs misread.
set(SVAPI_QUICKJS_TAG "v0.17.0" CACHE STRING "quickjs-ng git tag to vendor")

set(QJS_ENABLE_INSTALL OFF CACHE BOOL "" FORCE)   # quickjs must not land in our .deb
set(QJS_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(QJS_BUILD_LIBC OFF CACHE BOOL "" FORCE)       # no std/os modules: slice 1 has no filesystem
set(QJS_BUILD_CLI_WITH_MIMALLOC OFF CACHE BOOL "" FORCE)
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)

# quickjs-ng adds qjs/qjsc/api-test unconditionally; EXCLUDE_FROM_ALL keeps them
# out of our default build. The guard is for CMake < 3.28, where the option does
# not exist yet and the extra targets are merely wasted build time.
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28)
    FetchContent_Declare(quickjs
        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
        GIT_TAG        ${SVAPI_QUICKJS_TAG}
        GIT_SHALLOW    TRUE
        EXCLUDE_FROM_ALL)
else()
    FetchContent_Declare(quickjs
        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
        GIT_TAG        ${SVAPI_QUICKJS_TAG}
        GIT_SHALLOW    TRUE)
endif()
FetchContent_MakeAvailable(quickjs)

#
# libcurl, for the mail surface (IMAP + SMTP). Vendored by default.
#
# This is a DECISION, not a default. Linking Debian's libcurl would mean the
# distro's security team tracks curl CVEs for us and a fix reaches every
# deployed box through unattended-upgrades without us republishing anything.
# Vendoring gives that up, and the obligations that come with it are accepted
# deliberately:
#
#   1. CVE TRACKING IS NOW OURS. curl ships security advisories with most
#      releases, on a roughly 8-week cadence. A statically linked curl inside
#      our binaries is invisible to `apt` and to the distro's tooling, so a
#      vulnerable version sits on a customer box until somebody here notices.
#      A fix means a rebuild AND a republish of both binaries, not an apt
#      upgrade. Review at every curl release.
#   2. The pin is reviewed against WHAT THIS SERVICE ACTUALLY REACHES, not
#      against an advisory's severity score - the same discipline the
#      cpp-httplib pin uses, and the discipline that correctly ruled curl's
#      HTTP/3, proxy, NTLM and Kerberos surface out of scope here, because the
#      disable list below compiles all of it out.
#   3. The reachable protocol set is exactly: imaps, imap, smtps, smtp. An
#      advisory in any other protocol is not our exposure.
#
# curl-8_22_0 was released 2 Sep 2026; the next release is due 14 Oct 2026.
# curl's git tags are underscored, which is why this does not read 8.22.0.
#
# SFTP is deliberately NOT in the surface, which is what keeps this to ONE
# vendored upstream: SFTP would require libssh2 as well, and libssh2 is far
# less watched than curl while having had remotely reachable issues.
set(SVAPI_CURL_TAG "curl-8_22_0" CACHE STRING "curl git tag to vendor")
option(SVAPI_VENDOR_CURL "Vendor libcurl rather than linking the system one" ON)

if(SVAPI_VENDOR_CURL)
    # The disable list IS the attack surface of the pin, so it is explicit
    # rather than inherited from curl's defaults.
    set(BUILD_CURL_EXE OFF CACHE BOOL "" FORCE)        # the library, not the tool
    set(CURL_DISABLE_INSTALL ON CACHE BOOL "" FORCE)   # curl must not land in our .deb
    set(ENABLE_CURL_MANUAL OFF CACHE BOOL "" FORCE)
    set(CURL_USE_OPENSSL ON CACHE BOOL "" FORCE)       # the TLS backend everything else here uses
    set(CURL_USE_LIBSSH2 OFF CACHE BOOL "" FORCE)      # no SFTP, so no second upstream to track
    set(CURL_USE_LIBSSH OFF CACHE BOOL "" FORCE)
    set(CURL_USE_LIBPSL OFF CACHE BOOL "" FORCE)       # a cookie-domain concern; we have no cookies
    set(CURL_USE_GSSAPI OFF CACHE BOOL "" FORCE)
    set(CURL_ENABLE_SSL ON CACHE BOOL "" FORCE)
    set(ENABLE_THREADED_RESOLVER ON CACHE BOOL "" FORCE)
    set(USE_NGHTTP2 OFF CACHE BOOL "" FORCE)
    set(USE_NGTCP2 OFF CACHE BOOL "" FORCE)
    set(USE_QUICHE OFF CACHE BOOL "" FORCE)
    set(CURL_DISABLE_NTLM ON CACHE BOOL "" FORCE)
    # zlib, zstd and brotli are HTTP CONTENT ENCODINGS. With HTTP compiled out
    # they can never be reached, and left enabled they are found on the build
    # host and become real shared-library dependencies of the .deb for no
    # benefit. Turned off so the package's dependency list matches what the
    # code can actually use.
    set(CURL_ZLIB OFF CACHE STRING "" FORCE)
    set(CURL_ZSTD OFF CACHE STRING "" FORCE)
    set(CURL_BROTLI OFF CACHE STRING "" FORCE)
    # HTTP is compiled OUT on purpose. ctx.fetch is cpp-httplib, with its own
    # SSRF guard, its own address pinning and its own outbound defaults; two
    # HTTP clients with two sets of defaults is exactly how the two drift.
    # Consequence, recorded rather than discovered later: WebDAV/CalDAV are
    # HTTP and are therefore NOT in this slice. Re-enabling HTTP here also
    # brings redirects back, which would then need REDIR_PROTOCOLS_STR set
    # separately and FOLLOWLOCATION off.
    set(CURL_DISABLE_HTTP ON CACHE BOOL "" FORCE)
    # PROXY is compiled out rather than disabled per handle. curl reads
    # *_proxy and ALL_PROXY from the environment by default, and runner.env is
    # a file an operator edits; a proxy variable nobody intended to apply to
    # mail would silently reroute a destination the SSRF guard had already
    # approved, defeating the address pinning. Compiling it out cannot be
    # undone by a later patch that forgets to set CURLOPT_PROXY.
    set(CURL_DISABLE_PROXY ON CACHE BOOL "" FORCE)
    # NETRC off: credentials come from project secrets and nowhere else, never
    # from a file on disk.
    set(CURL_DISABLE_NETRC ON CACHE BOOL "" FORCE)
    # Each of these is persistent cross-request state, which is precisely what
    # a multi-tenant pool must not accumulate. Removing the feature beats
    # scrubbing it between tenants.
    set(CURL_DISABLE_COOKIES ON CACHE BOOL "" FORCE)
    set(CURL_DISABLE_ALTSVC ON CACHE BOOL "" FORCE)
    set(CURL_DISABLE_HSTS ON CACHE BOOL "" FORCE)
    foreach(_proto FILE DICT GOPHER LDAP LDAPS MQTT RTSP SMB TELNET TFTP WEBSOCKETS POP3 FTP)
        set(CURL_DISABLE_${_proto} ON CACHE BOOL "" FORCE)
    endforeach()

    if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28)
        FetchContent_Declare(curl
            GIT_REPOSITORY https://github.com/curl/curl.git
            GIT_TAG        ${SVAPI_CURL_TAG}
            GIT_SHALLOW    TRUE
            EXCLUDE_FROM_ALL)
    else()
        FetchContent_Declare(curl
            GIT_REPOSITORY https://github.com/curl/curl.git
            GIT_TAG        ${SVAPI_CURL_TAG}
            GIT_SHALLOW    TRUE)
    endif()
    FetchContent_MakeAvailable(curl)
    # curl detects the CA bundle AT CONFIGURE TIME and bakes the path in
    # (/etc/ssl/certs/ca-certificates.crt on Debian, which is the release build
    # host and the target both). TLS verification is on and never relaxed, so
    # without that file EVERY mail connection fails as mail_tls_untrusted - a
    # failure that looks like a broken server rather than a missing package.
    # That is why the runner package depends on ca-certificates.
    set(SVAPI_CURL_TARGET CURL::libcurl)
else()
    # The escape hatch, and what the dev loop uses: a system libcurl builds in
    # seconds where the vendored one takes minutes. It is NOT what ships.
    find_package(CURL REQUIRED)
    set(SVAPI_CURL_TARGET CURL::libcurl)
endif()

# Found by the root project already; the guard is what makes this directory
# usable on its own.
if(NOT TARGET nlohmann_json::nlohmann_json)
    find_package(nlohmann_json REQUIRED)
endif()

add_library(runner_core STATIC
    src/js_runtime.cpp)
target_include_directories(runner_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(runner_core PUBLIC nlohmann_json::nlohmann_json PRIVATE qjs)
target_compile_features(runner_core PUBLIC cxx_std_20)
set_target_properties(runner_core PROPERTIES POSITION_INDEPENDENT_CODE ON)

find_package(Threads REQUIRED)
target_link_libraries(runner_core PUBLIC Threads::Threads)

# Headers shared with the server: apikey.hpp (KeyScope) and
# functions/descriptor.hpp. Both are pure, which is why the protocol layer may
# use them without dragging in the database client.
set(SVAPI_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../src")

# /run, /validate and /health as JSON in, JSON out: no transport, no database,
# which is what keeps the protocol testable on the dev host.
add_library(runner_protocol STATIC
    src/run_service.cpp
    src/function_env.cpp
    src/runner_auth.cpp
    src/job_worker.cpp
    ${SVAPI_SRC_DIR}/functions/timezone.cpp)
target_include_directories(runner_protocol PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${SVAPI_SRC_DIR})
if(NOT TARGET spdlog::spdlog)
    find_package(spdlog REQUIRED)   # the job worker logs
endif()
target_link_libraries(runner_protocol PUBLIC
    runner_core nlohmann_json::nlohmann_json spdlog::spdlog)
target_compile_features(runner_protocol PUBLIC cxx_std_20)
set_target_properties(runner_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)

# The protocol host: libcurl plus the mail parsers, the budget split and the
# error map. A FOURTH library rather than part of runner_host, and the reason
# is testability: runner_host links vectorapi_core and the database client and
# therefore cannot be built on the dev host, so putting the IMAP and MIME code
# there would make the largest and most defect-prone piece of this feature the
# one piece only the Docker path can compile. That is backwards. runner_net
# links neither, so its tests run anywhere.
#
# The division of labour at the runner_host boundary is strict: runner_host
# converts JS values to a plain request struct and converts a plain result
# struct back, and does nothing else. No curl call, no IMAP knowledge and no
# timeout arithmetic above that line.
add_library(runner_net STATIC
    src/net/imap_commands.cpp
    src/net/imap_fetch.cpp
    src/net/mime_build.cpp
    src/net/curl_errors.cpp
    src/net/mail_session.cpp
    ${SVAPI_SRC_DIR}/functions/mime_words.cpp)
target_include_directories(runner_net PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${SVAPI_SRC_DIR})
if(NOT TARGET spdlog::spdlog)
    find_package(spdlog REQUIRED)
endif()
# curl is PUBLIC rather than PRIVATE only because the transport TEST includes
# curl/curl.h to name CURLcode values; nothing above runner_net touches curl.
target_link_libraries(runner_net PUBLIC
    nlohmann_json::nlohmann_json spdlog::spdlog Threads::Threads ${SVAPI_CURL_TARGET})
target_compile_features(runner_net PUBLIC cxx_std_20)
set_target_properties(runner_net PROPERTIES POSITION_INDEPENDENT_CODE ON)

if(BUILD_TESTS)
    # Same find-then-fetch dance as tests/CMakeLists.txt, guarded so that
    # wiring this directory into the root project does not fetch twice.
    if(NOT TARGET GTest::gtest_main)
        find_package(GTest QUIET)
        if(NOT GTest_FOUND)
            message(STATUS "GTest not found on the system - fetching googletest")
            FetchContent_Declare(googletest
                GIT_REPOSITORY https://github.com/google/googletest.git
                GIT_TAG        v1.15.2)
            set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
            FetchContent_MakeAvailable(googletest)
        endif()
    endif()
    include(GoogleTest)

    add_executable(test_js_runtime tests/js_runtime_test.cpp)
    target_link_libraries(test_js_runtime PRIVATE runner_core GTest::gtest_main)
    gtest_discover_tests(test_js_runtime PROPERTIES TIMEOUT 120)

    if(NOT TARGET OpenSSL::Crypto)
        find_package(OpenSSL REQUIRED)   # apikey.cpp uses RAND_bytes
    endif()
    # Compiles the two pure server sources directly rather than linking
    # vectorapi_core, the same approach tests/CMakeLists.txt uses, so this
    # target still builds where smartbotic-db-client cannot.
    add_executable(test_run_service
        tests/run_service_test.cpp
        ${SVAPI_SRC_DIR}/functions/descriptor.cpp
        ${SVAPI_SRC_DIR}/functions/cron.cpp
        ${SVAPI_SRC_DIR}/apikey.cpp)
    target_link_libraries(test_run_service PRIVATE
        runner_protocol OpenSSL::Crypto GTest::gtest_main)
    gtest_discover_tests(test_run_service PROPERTIES TIMEOUT 120)

    # The job worker's decisions - retry classification, backoff, the trigger
    # mapping - driven against a fake queue and a real engine.
    add_executable(test_job_worker
        tests/job_worker_test.cpp
        ${SVAPI_SRC_DIR}/functions/descriptor.cpp
        ${SVAPI_SRC_DIR}/functions/cron.cpp
        ${SVAPI_SRC_DIR}/apikey.cpp)
    target_link_libraries(test_job_worker PRIVATE
        runner_protocol OpenSSL::Crypto GTest::gtest_main)
    gtest_discover_tests(test_job_worker PROPERTIES TIMEOUT 120)

    # The prelude's argument checks, driven through the real engine with
    # recording bindings standing in for the native ones. This file was
    # committed without a target and so had never been compiled - exactly the
    # class of miss that let the job worker ship unwired.
    add_executable(test_host_prelude tests/host_prelude_test.cpp)
    target_compile_definitions(test_host_prelude PRIVATE
        SVAPI_HOST_PRELUDE_PATH="${CMAKE_CURRENT_SOURCE_DIR}/src/host_prelude.js")
    target_link_libraries(test_host_prelude PRIVATE runner_core GTest::gtest_main)
    gtest_discover_tests(test_host_prelude PROPERTIES TIMEOUT 120)

    # Intl.DateTimeFormat against real time zone answers. timezone.cpp is pure,
    # so it compiles in directly rather than dragging in the database client.
    add_executable(test_intl_shim
        tests/intl_shim_test.cpp
        ${SVAPI_SRC_DIR}/functions/timezone.cpp)
    target_include_directories(test_intl_shim PRIVATE ${SVAPI_SRC_DIR})
    target_link_libraries(test_intl_shim PRIVATE runner_core GTest::gtest_main)
    gtest_discover_tests(test_intl_shim PROPERTIES TIMEOUT 120)

    # ctx.env scoping and the runner's own authentication: both pure, and both
    # tenancy boundaries, so they are tested without an engine or a database.
    add_executable(test_runner_env_auth
        tests/function_env_test.cpp
        tests/runner_auth_test.cpp)
    target_link_libraries(test_runner_env_auth PRIVATE runner_protocol GTest::gtest_main)
    gtest_discover_tests(test_runner_env_auth)

    # The mail surface's pure halves: command construction (the injection
    # boundary), response interpretation, message assembly, the budget split
    # and the error map. All of it runs with no network, which is the whole
    # reason runner_net is a separate target.
    add_executable(test_mail_pure
        tests/imap_commands_test.cpp
        tests/imap_fetch_test.cpp
        tests/mime_build_test.cpp
        tests/mail_net_test.cpp)
    target_link_libraries(test_mail_pure PRIVATE runner_net GTest::gtest_main)
    gtest_discover_tests(test_mail_pure PROPERTIES TIMEOUT 120)

    # The transport, driven against in-process fake IMAP and SMTP servers on
    # ephemeral loopback ports. Not a mock of curl: real curl, real sockets,
    # which is the only way the facts about what curl puts on the wire stay
    # true rather than becoming assumptions.
    add_executable(test_mail_session tests/mail_session_test.cpp)
    target_include_directories(test_mail_session PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)
    target_link_libraries(test_mail_session PRIVATE runner_net GTest::gtest_main)
    gtest_discover_tests(test_mail_session PROPERTIES TIMEOUT 120)
endif()

# The host bindings: the ctx.* surface. A SEPARATE target from runner_core
# because this is the half that links vectorapi_core and the database client,
# which is exactly why runner_core itself still builds and tests on the dev
# host (CLAUDE.md). Guarded, so configuring runner/ standalone still works.
if(TARGET vectorapi_core)
    # The JS prelude is embedded as a raw string literal, so the binary carries
    # no runtime file dependency: a deployed runner cannot be made to execute a
    # different prelude by swapping a file beside it.
    set(SVAPI_HOST_PRELUDE "${CMAKE_CURRENT_SOURCE_DIR}/src/host_prelude.js")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${SVAPI_HOST_PRELUDE}")
    file(READ "${SVAPI_HOST_PRELUDE}" SVAPI_HOST_PRELUDE_TEXT)
    file(CONFIGURE
        OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/host_prelude_js.hpp"
        CONTENT "#pragma once
// GENERATED from runner/src/host_prelude.js - do not edit.
namespace svapi::runner::generated {
inline constexpr const char* kHostPreludeJs = R\"JS(
${SVAPI_HOST_PRELUDE_TEXT})JS\";
} // namespace svapi::runner::generated
"
        @ONLY)

    add_library(runner_host STATIC src/host_context.cpp)
    target_include_directories(runner_host PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/generated)
    # qjs again, PRIVATE on runner_core: host_context.cpp includes quickjs.h.
    # runner_net carries the mail transport that ctx.mail binds to. PUBLIC so
    # the host-context tests, which link runner_host, can name its types.
    target_link_libraries(runner_host PUBLIC runner_core vectorapi_core runner_net PRIVATE qjs)
    target_compile_features(runner_host PUBLIC cxx_std_20)
    set_target_properties(runner_host PROPERTIES POSITION_INDEPENDENT_CODE ON)

    if(BUILD_TESTS)
        add_executable(test_host_context tests/host_context_test.cpp)
        target_link_libraries(test_host_context PRIVATE runner_host GTest::gtest_main)
        gtest_discover_tests(test_host_context PROPERTIES TIMEOUT 120)
    endif()
endif()

# The binary links vectorapi_core (registry + gateway) and host_context.cpp, and
# includes <svapi/version.hpp>, which only the root project generates. So it
# exists only inside the root project; a standalone runner build stops at the
# protocol layer and its tests.
if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
    add_executable(smartbotic-vectorapi-runner src/main.cpp)
    target_link_libraries(smartbotic-vectorapi-runner PRIVATE
        runner_protocol runner_host vectorapi_core
        $<$<BOOL:${SYSTEMD_FOUND}>:PkgConfig::SYSTEMD>)
    if(SYSTEMD_FOUND)
        target_compile_definitions(smartbotic-vectorapi-runner PRIVATE HAVE_SYSTEMD)
    endif()
    install(TARGETS smartbotic-vectorapi-runner RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
