package com.lingniu.ingest.api.pipeline;

import java.util.HashMap;
import java.util.Map;

/**
 * 一次消息处理的上下文，贯穿整个拦截链与 Handler。线程不共享，不需要同步。
 *
 * <p>attributes 用于在入口、拦截器、Dispatcher 之间传递轻量元数据，例如 traceId、归档 URI、
 * 鉴权结果等；不要放大对象或长期缓存，避免高频上报时放大内存占用。
 */
public final class IngestContext {

    private final String traceId;
    private final Map<String, Object> attributes = new HashMap<>(8);
    private volatile boolean aborted;
    private volatile String abortReason;

    public IngestContext(String traceId) {
        this.traceId = traceId;
    }

    public String traceId() {
        return traceId;
    }

    public <T> T attr(String key) {
        @SuppressWarnings("unchecked")
        T v = (T) attributes.get(key);
        return v;
    }

    public void attr(String key, Object value) {
        attributes.put(key, value);
    }

    public void abort(String reason) {
        // reason 会进入日志/诊断信息，保持短小、机器可读，方便定位是去重、限流还是鉴权失败。
        this.aborted = true;
        this.abortReason = reason;
    }

    public boolean aborted() {
        return aborted;
    }

    public String abortReason() {
        return abortReason;
    }
}
