package com.centreproject.framework.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author zhonglei.xu
 */
@Configuration
public class VirtualThreadConfig {
    private static final Logger log = LoggerFactory.getLogger(VirtualThreadConfig.class);

    @Bean
    public Executor virtualThreadExecutor() {
        ThreadFactory factory = Thread.ofVirtual()
                .name("vt-sync-", 1)
                .uncaughtExceptionHandler((t, e) ->
                        log.error("VirtualThread {} error", t.getName(), e))
                .factory();

        // 包装原始Executor以传递MDC
        return task -> {
            // 捕获当前MDC
            Map<String, String> context = MDC.getCopyOfContextMap();
            Executors.newThreadPerTaskExecutor(factory).execute(() -> {
                try {
                    // 设置到虚拟线程
                    MDC.setContextMap(context);
                    task.run();
                } finally {
                    MDC.clear();
                }
            });
        };
    }
}