/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <httpd.h>

#include <http_config.h>
#include <http_log.h>

#include <apr_atomic.h>
#include <apr_pools.h>
#include <apr_thread_mutex.h>

#include "h3.h"
#include "h3_io.h"
#include "h3_session.h"
#include "h3_threads.h"
#include "mod_http3.h"
#include "quic/h3q.h"
#include "quic/h3q_conn.h"

#define H3_PUMP_BUDGET 32

apr_status_t h3_thread_safe_pool_create(apr_pool_t* parent, const char* tag, apr_pool_t** out)
{
    apr_allocator_t* allocator = NULL;
    apr_thread_mutex_t* mutex = NULL;
    apr_status_t rv = apr_allocator_create(&allocator);
    if (rv != APR_SUCCESS)
    {
        return rv;
    }
    rv = apr_pool_create_ex(out, parent, NULL, allocator);
    if (rv != APR_SUCCESS)
    {
        apr_allocator_destroy(allocator);
        return rv;
    }
    apr_allocator_owner_set(allocator, *out);
    apr_pool_tag(*out, tag);
    rv = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_DEFAULT, *out);
    if (rv != APR_SUCCESS)
    {
        apr_pool_destroy(*out);
        *out = NULL;
        return rv;
    }
    apr_allocator_mutex_set(allocator, mutex);
    return APR_SUCCESS;
}

void* APR_THREAD_FUNC h3_event_thread(apr_thread_t* thread, void* data)
{
    (void)thread;
    h3_io_t* io = data;
    if (!io)
    {
        ap_log_perror(APLOG_MARK, APLOG_ERR, 0, NULL, "h3_event_thread: NULL io");
        return NULL;
    }
    ap_log_error(APLOG_MARK, APLOG_INFO, 0, io->server, "event thread started");
    int work_pending = 0;
    int listener_failed = 0;
    while (io->thread_running || io->active_sessions->nelts > 0)
    {
        if (!work_pending)
        {
            wait_for_event(io);
        }
        work_pending = 0;
        {
            int pump_rounds = 0;
            int pumped;
            do {
                pumped = h3q_engine_pump(io->qengine);
                if (pumped < 0)
                {
                    if (!listener_failed)
                    {
                        listener_failed = 1;
                        ap_log_error(APLOG_MARK, APLOG_ERR, 0, io->server, "QUIC listener event processing failed; no further datagrams will be handled");
                    }
                    apr_sleep(apr_time_from_msec(H3_LISTENER_FAILED_BACKOFF_MS));
                    break;
                }
                listener_failed = 0;
                if (pumped > 0)
                {
                    work_pending = 1;
                }
            } while (pumped > 0 && ++pump_rounds < H3_PUMP_BUDGET);
        }

        if (io->thread_running)
        {
            for (;;)
            {
                h3q_conn* conn = h3q_engine_accept_conn(io->qengine);
                if (!conn)
                {
                    break;
                }
                /* The engine has already answered these clients: refuse them, or they wait out their idle timeout. */
                if (io->draining)
                {
                    h3q_conn_refuse(io->qengine, conn); /* no new connections during a graceful stop */
                    continue;
                }
                ap_log_error(APLOG_MARK, APLOG_INFO, 0, io->server, "accepted new QUIC connection");
                if (h3_io_at_connection_limit(io))
                {
                    h3_server_conf* conf = ap_get_module_config(io->server->module_config, &http3_module);
                    ap_log_error(APLOG_MARK, APLOG_WARNING, 0, io->server, "dropping QUIC connection: at H3MaxConnections limit (%u)", conf->h3_max_connections);
                    h3q_conn_refuse(io->qengine, conn);
                    continue;
                }
                if (!prepare_accepted_connection(io, conn))
                {
                    h3q_conn_free(conn);
                }
            }
        }
        if (io->thread_running)
        {
            /* Also while draining: a pending handshake counts as an MPM connection, so it must finish or time out. */
            progress_pending_handshakes(io);
        }

        apr_time_t now = apr_time_now();
        for (int i = 0; i < io->active_sessions->nelts;)
        {
            if (i > 0 && (i % 8) == 0)
            {
                int p = h3q_engine_pump(io->qengine);
                if (p > 0)
                {
                    work_pending = 1;
                }
            }

            h3_session* session = ((h3_session**)io->active_sessions->elts)[i];

            /* Skip a session with nothing new: no busy worker, no packet, timer or
             * stream limit change in the engine, no worker output. The sweep still
             * serves it once a second, for its idle and stream timeouts. Every session
             * keeps its control streams, so a stream count cannot tell idle sessions. */
            if (!io->draining && io->thread_running && !session->aborted
                && apr_atomic_read32(&session->active_tasks) == 0
                && !h3q_conn_take_activity(session->qconn)
                && !apr_atomic_xchg32(&session->wake, 0)
                && now < session->next_sweep)
            {
                i++;
                continue;
            }
            session->next_sweep = now + apr_time_from_sec(1);

            if (!session->aborted && service_session_pass(io, session))
            {
                work_pending = 1;
                apr_atomic_set32(&session->wake, 1); /* the pass ran out of budget: serve it again next round */
            }

            if (session->aborted)
            {
                int is_rapid = (!io->thread_running || io->draining);
                int shutdown_done = h3q_conn_shutdown(session->qconn, is_rapid, session->abort_quic_error_code, session->ngh3_dead ? session->abort_reason : NULL);

                if (shutdown_done && apr_atomic_read32(&session->active_tasks) == 0)
                {
                    ap_log_error(APLOG_MARK, APLOG_INFO, 0, io->server, "connection servicing done");
                    h3_session_destroy(session);
                    if (io->note_conn_removed)
                    {
                        io->note_conn_removed();
                    }
                    if (i < io->active_sessions->nelts - 1)
                    {
                        ((h3_session**)io->active_sessions->elts)[i] = ((h3_session**)io->active_sessions->elts)[io->active_sessions->nelts - 1];
                    }
                    io->active_sessions->nelts--;
                    apr_atomic_dec32(&io->active_session_count);
                    continue; /* Do not increment i: the last element was swapped into this slot. */
                }
            }
            i++;
        }
    }
    while (io->pending_handshakes->nelts > 0)
    {
        h3_pending_handshake* pending = (h3_pending_handshake*)io->pending_handshakes->elts;
        h3q_conn_shutdown(pending[0].conn, 1, 0, NULL);
        remove_pending_handshake(io, 0, 1);
    }
    ap_log_error(APLOG_MARK, APLOG_INFO, 0, io->server, "event thread exiting");
    return NULL;
}
