001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.kryo;
015
016import ch.qos.logback.classic.spi.ILoggingEvent;
017import ch.qos.logback.core.encoder.EncoderBase;
018import com.esotericsoftware.kryo.kryo5.Kryo;
019import com.esotericsoftware.kryo.kryo5.io.Output;
020
021import static ch.qos.logback.classic.kryo.KryoClassicConstants.*;
022
023public class KryoEncoder extends EncoderBase<ILoggingEvent> {
024
025
026    public enum SerializerType {
027        Vanilla,
028        Custom
029    };
030
031    static int MAX_BUFFER_SIZE = 1024 * 64;
032
033    Kryo kryo;
034    byte[] buffer = new byte[MAX_BUFFER_SIZE];
035    Output output = new Output(buffer);
036
037    SerializerType serializerType = SerializerType.Custom;
038    byte streamVersion = STREAM_VERSION_5;
039    /** True once {@link #setStreamVersion(int)} was called, e.g. from configuration. */
040    boolean streamVersionExplicitlySet = false;
041
042    int eventsInEpoch;
043    int maxEventsBeforeReset = DEFAULT_MAX_EVENTS_BEFORE_RESET;
044
045    @Override
046    public void start() {
047        // Vanilla streams are unframed and always carry version 0
048        if (serializerType == SerializerType.Vanilla && streamVersion != STREAM_VERSION_0) {
049            // the default stream version applies to Custom; warn only about an explicit setting
050            if (streamVersionExplicitlySet) {
051                addWarn("Stream version " + streamVersion + " is not applicable to the Vanilla serializer type. Using stream version "
052                        + STREAM_VERSION_0 + " instead.");
053            }
054            this.streamVersion = STREAM_VERSION_0;
055        }
056        this.kryo = makeFreshKryo();
057        if(kryo == null) {
058            addError("Kryo serializer is null");
059            return;
060        }
061        this.eventsInEpoch = 0;
062        super.start();
063    }
064
065    @Override
066    public boolean isStateful() {
067        return true;
068    }
069
070    boolean isFramed() {
071        return KryoClassicConstants.isFramed(streamVersion);
072    }
073
074    public int getMaxEventsBeforeReset() {
075        return maxEventsBeforeReset;
076    }
077
078    public void setMaxEventsBeforeReset(int maxEventsBeforeReset) {
079        if (maxEventsBeforeReset < 1) {
080            throw new IllegalArgumentException("maxEventsBeforeReset must be >= 1");
081        }
082        this.maxEventsBeforeReset = maxEventsBeforeReset;
083    }
084
085    Kryo makeFreshKryo() {
086        return KryoBuilder.build(serializerType, streamVersion);
087    }
088
089    public void setSerializerType(SerializerType serializerType) {
090        this.serializerType = serializerType;
091    }
092
093    public SerializerType getSerializerType() {
094        return serializerType;
095    }
096
097    /**
098     * Stream format version written into the header: {@link KryoClassicConstants#STREAM_VERSION_0}
099     * for Vanilla, {@link KryoClassicConstants#STREAM_VERSION_5} for Custom
100     * ({@link LoggingEventKryoVOSerializerV5}, framed with {@link StreamFrameV5}).
101     */
102    public void setStreamVersion(int streamVersion) {
103        this.streamVersion = (byte) streamVersion;
104        this.streamVersionExplicitlySet = true;
105    }
106
107    public byte getStreamVersion() {
108        return streamVersion;
109    }
110
111    /**
112     * Fixed stream preamble: magic (4) + version (1) + flags (1).
113     * Written once at the start of the stream by the appender.
114     */
115    @Override
116    public byte[] headerBytes() {
117        byte flags = (serializerType == SerializerType.Custom) ? FLAG_CUSTOM_SERIALIZER : 0;
118        return new byte[] {
119                STREAM_MAGIC[0], STREAM_MAGIC[1], STREAM_MAGIC[2], STREAM_MAGIC[3],
120                streamVersion,
121                flags
122        };
123    }
124
125    @Override
126    synchronized public byte[] encode(ILoggingEvent loggingEvent) {
127        LoggingEventKryoVO loggerEventKryoVO = new LoggingEventKryoVO(loggingEvent);
128        if (!isFramed()) {
129            output.setPosition(0);
130            kryo.writeObject(output, loggerEventKryoVO);
131            output.flush();
132            return copyOf(buffer, 0, output.position());
133        }
134
135        int reserved = StreamFrameV5.MAX_PREFIX;
136        output.setPosition(reserved);
137        kryo.writeObject(output, loggerEventKryoVO);
138        output.flush();
139        int payloadLen = output.position() - reserved;
140        int prefixLen = StreamFrameV5.writeEventPrefix(buffer, reserved, payloadLen);
141        int start = reserved - prefixLen;
142        int framedLen = prefixLen + payloadLen;
143        eventsInEpoch++;
144        if (eventsInEpoch < maxEventsBeforeReset) {
145            return copyOf(buffer, start, framedLen);
146        }
147        byte[] close = StreamFrameV5.closeCode();
148        byte[] header = headerBytes();
149        byte[] out = new byte[framedLen + close.length + header.length];
150        System.arraycopy(buffer, start, out, 0, framedLen);
151        System.arraycopy(close, 0, out, framedLen, close.length);
152        System.arraycopy(header, 0, out, framedLen + close.length, header.length);
153        resetEpoch();
154        return out;
155    }
156
157    private static byte[] copyOf(byte[] src, int off, int len) {
158        byte[] out = new byte[len];
159        System.arraycopy(src, off, out, 0, len);
160        return out;
161    }
162
163    @Override
164    synchronized public byte[] footerBytes() {
165        if (isFramed() && eventsInEpoch > 0) {
166            resetEpoch();
167            return StreamFrameV5.closeCode();
168        }
169        resetEpoch();
170        return new byte[0];
171    }
172
173    private void resetEpoch() {
174        eventsInEpoch = 0;
175        kryo = makeFreshKryo();
176        if (kryo == null) {
177            addError("Kryo serializer is null");
178        }
179    }
180}