<commit_before>package com.firefly.server.http2;

import com.firefly.codec.http2.decode.HttpParser;
import com.firefly.codec.http2.decode.HttpParser.RequestHandler;
import com.firefly.codec.http2.decode.HttpParser.ResponseHandler;
import com.firefly.codec.http2.decode.SettingsBodyParser;
import com.firefly.codec.http2.encode.HttpGenerator;
import com.firefly.codec.http2.frame.HeadersFrame;
import com.firefly.codec.http2.frame.PrefaceFrame;
import com.firefly.codec.http2.frame.SettingsFrame;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.stream.*;
import com.firefly.net.SecureSession;
import com.firefly.net.Session;
import com.firefly.utils.Assert;
import com.firefly.utils.codec.Base64Utils;
import com.firefly.utils.concurrent.Callback;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.lang.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.CONTINUE_100_BYTES;
import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.H2C_BYTES;

public class HTTP1ServerConnection extends AbstractHTTP1Connection implements HTTPServerConnection {

    protected static final Logger log = LoggerFactory.getLogger("firefly-system");

    private final ServerSessionListener serverSessionListener;
    private final HTTP1ServerRequestHandler serverRequestHandler;
    AtomicBoolean upgradeHTTP2Complete = new AtomicBoolean(false);
    Promise<HTTPTunnelConnection> tunnelConnectionPromise;

    HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession,
                          HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) {
        super(config, secureSession, tcpSession, requestHandler, null);
        requestHandler.connection = this;
        this.serverSessionListener = serverSessionListener;
        this.serverRequestHandler = requestHandler;
    }

    @Override
    protected HttpParser initHttpParser(HTTP2Configuration config, RequestHandler requestHandler, ResponseHandler responseHandler) {
        return new HttpParser(requestHandler, config.getMaxRequestHeadLength());
    }

    HttpParser getParser() {
        return parser;
    }

    SecureSession getSecureSession() {
        return secureSession;
    }

    Session getTcpSession() {
        return tcpSession;
    }

    HTTP2Configuration getHTTP2Configuration() {
        return config;
    }

    public MetaData.Request getRequest() {
        return serverRequestHandler.request;
    }

    public MetaData.Response getResponse() {
        return serverRequestHandler.response;
    }

    void response100Continue() {
        serverRequestHandler.outputStream.response100Continue();
    }

    private void responseH2c() {
        serverRequestHandler.outputStream.responseH2c();
    }

    @Override
    public void upgradeHTTPTunnel(Promise<HTTPTunnelConnection> tunnelConnectionPromise) {
        this.tunnelConnectionPromise = tunnelConnectionPromise;
    }

    @Override
    public CompletableFuture<HTTPTunnelConnection> upgradeHTTPTunnel() {
        Promise.Completable<HTTPTunnelConnection> c = new Promise.Completable<>();
        tunnelConnectionPromise = c;
        return c;
    }

    HTTP1ServerTunnelConnection createHTTPTunnel() {
        if (tunnelConnectionPromise != null) {
            HTTP1ServerTunnelConnection tunnelConnection = new HTTP1ServerTunnelConnection(secureSession, tcpSession, httpVersion);
            tunnelConnectionPromise.succeeded(tunnelConnection);
            tcpSession.attachObject(tunnelConnection);
            return tunnelConnection;
        } else {
            return null;
        }
    }

    static class HTTP1ServerResponseOutputStream extends AbstractHTTP1OutputStream {

        private final HTTP1ServerConnection connection;
        private final HttpGenerator httpGenerator;

        HTTP1ServerResponseOutputStream(MetaData.Response response, HTTP1ServerConnection connection) {
            super(response, false);
            this.connection = connection;
            httpGenerator = new HttpGenerator(true, true);
        }

        HTTP1ServerConnection getHTTP1ServerConnection() {
            return connection;
        }

        void responseH2c() {
//            getSession().encode(ByteBuffer.wrap(H2C_BYTES));
            CompletableFuture<Boolean> future = new CompletableFuture<>();
            getSession().write(ByteBuffer.wrap(H2C_BYTES), new Callback() {
                @Override
                public void succeeded() {
                    future.complete(true);
                }

                @Override
                public void failed(Throwable x) {
                    future.completeExceptionally(x);
                }
            });
            try {
                future.get(2, TimeUnit.SECONDS);
            } catch (Exception e) {
                log.error("Write h2c response exception", e);
            }
        }

        void response100Continue() {
            getSession().encode(ByteBuffer.wrap(CONTINUE_100_BYTES));
        }

        @Override
        protected void generateHTTPMessageSuccessfully() {
            log.debug("server session {} generates the HTTP message completely", connection.getSessionId());

            final MetaData.Response response = connection.getResponse();
            final MetaData.Request request = connection.getRequest();

            String requestConnectionValue = request.getFields().get(HttpHeader.CONNECTION);
            String responseConnectionValue = response.getFields().get(HttpHeader.CONNECTION);

            switch (request.getHttpVersion()) {
                case HTTP_1_0:<commit_msg>[test]: test h2c<commit_after>package com.firefly.server.http2;

import com.firefly.codec.http2.decode.HttpParser;
import com.firefly.codec.http2.decode.HttpParser.RequestHandler;
import com.firefly.codec.http2.decode.HttpParser.ResponseHandler;
import com.firefly.codec.http2.decode.SettingsBodyParser;
import com.firefly.codec.http2.encode.HttpGenerator;
import com.firefly.codec.http2.frame.HeadersFrame;
import com.firefly.codec.http2.frame.PrefaceFrame;
import com.firefly.codec.http2.frame.SettingsFrame;
import com.firefly.codec.http2.model.*;
import com.firefly.codec.http2.stream.*;
import com.firefly.net.SecureSession;
import com.firefly.net.Session;
import com.firefly.utils.Assert;
import com.firefly.utils.codec.Base64Utils;
import com.firefly.utils.concurrent.Callback;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.lang.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.CONTINUE_100_BYTES;
import static com.firefly.codec.http2.encode.PredefinedHTTP1Response.H2C_BYTES;

public class HTTP1ServerConnection extends AbstractHTTP1Connection implements HTTPServerConnection {

    protected static final Logger log = LoggerFactory.getLogger("firefly-system");

    private final ServerSessionListener serverSessionListener;
    private final HTTP1ServerRequestHandler serverRequestHandler;
    AtomicBoolean upgradeHTTP2Complete = new AtomicBoolean(false);
    Promise<HTTPTunnelConnection> tunnelConnectionPromise;

    HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession,
                          HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) {
        super(config, secureSession, tcpSession, requestHandler, null);
        requestHandler.connection = this;
        this.serverSessionListener = serverSessionListener;
        this.serverRequestHandler = requestHandler;
    }

    @Override
    protected HttpParser initHttpParser(HTTP2Configuration config, RequestHandler requestHandler, ResponseHandler responseHandler) {
        return new HttpParser(requestHandler, config.getMaxRequestHeadLength());
    }

    HttpParser getParser() {
        return parser;
    }

    SecureSession getSecureSession() {
        return secureSession;
    }

    Session getTcpSession() {
        return tcpSession;
    }

    HTTP2Configuration getHTTP2Configuration() {
        return config;
    }

    public MetaData.Request getRequest() {
        return serverRequestHandler.request;
    }

    public MetaData.Response getResponse() {
        return serverRequestHandler.response;
    }

    void response100Continue() {
        serverRequestHandler.outputStream.response100Continue();
    }

    private void responseH2c() {
        serverRequestHandler.outputStream.responseH2c();
    }

    @Override
    public void upgradeHTTPTunnel(Promise<HTTPTunnelConnection> tunnelConnectionPromise) {
        this.tunnelConnectionPromise = tunnelConnectionPromise;
    }

    @Override
    public CompletableFuture<HTTPTunnelConnection> upgradeHTTPTunnel() {
        Promise.Completable<HTTPTunnelConnection> c = new Promise.Completable<>();
        tunnelConnectionPromise = c;
        return c;
    }

    HTTP1ServerTunnelConnection createHTTPTunnel() {
        if (tunnelConnectionPromise != null) {
            HTTP1ServerTunnelConnection tunnelConnection = new HTTP1ServerTunnelConnection(secureSession, tcpSession, httpVersion);
            tunnelConnectionPromise.succeeded(tunnelConnection);
            tcpSession.attachObject(tunnelConnection);
            return tunnelConnection;
        } else {
            return null;
        }
    }

    static class HTTP1ServerResponseOutputStream extends AbstractHTTP1OutputStream {

        private final HTTP1ServerConnection connection;
        private final HttpGenerator httpGenerator;

        HTTP1ServerResponseOutputStream(MetaData.Response response, HTTP1ServerConnection connection) {
            super(response, false);
            this.connection = connection;
            httpGenerator = new HttpGenerator(true, true);
        }

        HTTP1ServerConnection getHTTP1ServerConnection() {
            return connection;
        }

        void responseH2c() {
            getSession().encode(ByteBuffer.wrap(H2C_BYTES));
        }

        void response100Continue() {
            getSession().encode(ByteBuffer.wrap(CONTINUE_100_BYTES));
        }

        @Override
        protected void generateHTTPMessageSuccessfully() {
            log.debug("server session {} generates the HTTP message completely", connection.getSessionId());

            final MetaData.Response response = connection.getResponse();
            final MetaData.Request request = connection.getRequest();

            String requestConnectionValue = request.getFields().get(HttpHeader.CONNECTION);
            String responseConnectionValue = response.getFields().get(HttpHeader.CONNECTION);

            switch (request.getHttpVersion()) {
                case HTTP_1_0:
{'fraction_non_alphanumeric': 0.07944822769338222, 'fraction_numerical': 0.011000523834468309, 'mean_word_length': 3.4485436893203882, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4628971', 'n_tokens_mistral': 2941, 'n_tokens_neox': 2862, 'n_words': 542}