All files / packages/dataflint-mcp/src state.ts

89.85% Statements 124/138
100% Branches 25/25
61.11% Functions 11/18
89.85% Lines 124/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231  1x 1x                             1x 99x 99x 99x 99x 99x   99x   99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x           99x                 99x       99x       99x                 99x                 99x       99x 6x 6x 7x 7x 6x 6x   99x       99x 11x 11x 11x 11x 1x 1x   10x 11x 12x 12x 10x 11x   99x 13x 13x 13x 13x   13x 3x 3x   10x   13x 11x 11x 10x 10x 11x   10x   10x 10x 10x 10x   10x 13x   99x 10x 10x 2x 2x   8x 8x 10x 10x             99x 9x 9x             99x 12x 12x           99x     2x 2x   99x 6x 6x 6x 6x 6x 6x 6x           99x                       2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 99x  
import { Job, SqlQueriesCode, Node } from "./dataflint-server-models";
import { Logger } from "./logger";
import { ResourceState } from "./resource-state";
 
/**
 * DataFlint MCP State management class
 *
 * This class manages the state for MCP operations, including:
 * - Job caching with automatic cleanup (keeps last 1000 jobs)
 * - Job ID to Job object mapping for quick lookups
 * - SQL plans caching by job ID (keeps last 10 job plans)
 * - Generated code caching by job ID (keeps last 10 job codes)
 * - Mapping hash tracking per job (for cache invalidation)
 *
 * Note: Session ID tracking is now handled by AsyncLocalStorage in request-context.ts
 * to prevent race conditions with concurrent requests.
 */
export class DataFlintMcpState {
    private jobsState: ResourceState<Job>;
    private jobPlansState: ResourceState<any>;
    private generatedCodeState: ResourceState<SqlQueriesCode>;
    private enrichedSqlState: ResourceState<Map<number, any>>;
    private nodeIndexState: ResourceState<Map<number, Map<number, Node>>>;
    // Mapping hash tracking for highlight cache invalidation
    private mappingHashState: ResourceState<string>;
 
    constructor() {
        const logger = Logger.getInstance();
        this.jobsState = new ResourceState<Job>("jobs", 1000);
        this.jobPlansState = new ResourceState<any>("jobPlans", 1000);
        this.generatedCodeState = new ResourceState<SqlQueriesCode>(
            "generatedCode",
            10
        );
        this.enrichedSqlState = new ResourceState<Map<number, any>>(
            "enrichedSql",
            30
        );
        this.nodeIndexState = new ResourceState<Map<number, Map<number, Node>>>(
            "nodeIndex",
            30
        );
        this.mappingHashState = new ResourceState<string>("mappingHash", 100);
        logger.info("DataFlintMcpState initialized");
    }
 
    /**
     * Update application jobs - saves jobs with job id mapping and manages job limit
     * @param jobs Array of jobs to save
     */
    updateApplicationJobs(jobs: Job[]): void {
        this.jobsState.updateResources(jobs, (job: Job) => job.id);
    }
 
    /**
     * Get a job by ID
     * @param jobId The ID of the job to retrieve
     * @returns The job object or undefined if not found
     */
    getJob(jobId: number): Job | undefined {
        return this.jobsState.getResource(jobId);
    }
 
    updateJobPlan(jobId: number, plan: any): void {
        this.jobPlansState.setResource(jobId, plan);
    }
 
    getJobPlan(jobId: number): any | undefined {
        return this.jobPlansState.getResource(jobId);
    }
 
    /**
     * Update generated code - saves generated code with cache key and manages limit
     * @param cacheKey The cache key (format: "jobId-optimize") for this generated code
     * @param code Array of SQL query code for this job
     */
    updateJobGeneratedCode(cacheKey: string, code: SqlQueriesCode): void {
        this.generatedCodeState.setResource(cacheKey, code);
    }
 
    /**
     * Get generated code by cache key
     * @param cacheKey The cache key (format: "jobId-optimize") to get generated code for
     * @returns Array of SQL query code or undefined if not found
     */
    getJobGeneratedCode(cacheKey: string): SqlQueriesCode | undefined {
        return this.generatedCodeState.getResource(cacheKey);
    }
 
    updateJobEnrichedSql(jobId: number, enrichedSqlList: any[]): void {
        const enrichedSqlMap = new Map<number, any>();
        for (const sql of enrichedSqlList) {
            enrichedSqlMap.set(sql.id, sql);
        }
        this.enrichedSqlState.setResource(jobId, enrichedSqlMap);
    }
 
    getJobEnrichedSql(jobId: number): Map<number, any> | undefined {
        return this.enrichedSqlState.getResource(jobId);
    }
 
    private buildNodeIndex(
        sqlId: number,
        enrichedSql: any
    ): Map<number, Node> | undefined {
        if (!enrichedSql.nodes || !Array.isArray(enrichedSql.nodes)) {
            return undefined;
        }
 
        const nodeMap = new Map<number, Node>();
        for (const node of enrichedSql.nodes) {
            nodeMap.set(node.id, node);
        }
        return nodeMap;
    }
 
    getOrBuildNodeIndex(
        jobId: number,
        enrichedSqlMap: Map<number, any>
    ): Map<number, Map<number, Node>> {
        let nodeIndex = this.nodeIndexState.getResource(jobId);
 
        if (nodeIndex) {
            return nodeIndex;
        }
 
        nodeIndex = new Map<number, Map<number, Node>>();
 
        for (const [sqlId, enrichedSql] of enrichedSqlMap.entries()) {
            const sqlNodeIndex = this.buildNodeIndex(sqlId, enrichedSql);
            if (sqlNodeIndex) {
                nodeIndex.set(sqlId, sqlNodeIndex);
            }
        }
 
        this.nodeIndexState.setResource(jobId, nodeIndex);
 
        const logger = Logger.getInstance();
        logger.debug(
            `Built node index for job ${jobId}: ${nodeIndex.size} SQLs indexed`
        );
 
        return nodeIndex;
    }
 
    getNode(jobId: number, sqlId: number, nodeId: number): Node | undefined {
        const enrichedSqlMap = this.enrichedSqlState.getResource(jobId);
        if (!enrichedSqlMap) {
            return undefined;
        }
 
        const nodeIndex = this.getOrBuildNodeIndex(jobId, enrichedSqlMap);
        const sqlIndex = nodeIndex.get(sqlId);
        return sqlIndex?.get(nodeId);
    }
 
    /**
     * Store mapping hash for a job (for cache invalidation)
     * @param jobId The job ID
     * @param hash The mapping hash from server response
     */
    setMappingHash(jobId: number, hash: string): void {
        this.mappingHashState.setResource(jobId, hash);
    }
 
    /**
     * Get mapping hash for a job
     * @param jobId The job ID
     * @returns The mapping hash or undefined if not cached
     */
    getMappingHash(jobId: number): string | undefined {
        return this.mappingHashState.getResource(jobId);
    }
 
    /**
     * Clear mapping hash for a job (used on remap)
     * @param jobId The job ID
     */
    clearMappingHash(jobId: number): void {
        // Resource state doesn't have a delete method, so we set to empty string
        // which will be treated as "no cache" by the logic
        this.mappingHashState.setResource(jobId, "");
    }
 
    clearResources(): void {
        this.jobsState.clearResources();
        this.jobPlansState.clearResources();
        this.generatedCodeState.clearResources();
        this.enrichedSqlState.clearResources();
        this.nodeIndexState.clearResources();
        this.mappingHashState.clearResources();
    }
 
    /**
     * Get state statistics for debugging
     * @returns Object with state statistics
     */
    getStateStats(): {
        jobCount: number;
        maxJobs: number;
        oldestJobId: number | null;
        newestJobId: number | null;
        jobIds: number[];
        generatedCodeCount: number;
        generatedCodeJobIds: number[];
        nodeIndexCount: number;
        nodeIndexJobIds: number[];
        mappingHashCount: number;
        mappingHashJobIds: number[];
    } {
        const jobStats = this.jobsState.getStats();
        const generatedCodeStats = this.generatedCodeState.getStats();
        const nodeIndexStats = this.nodeIndexState.getStats();
        const mappingHashStats = this.mappingHashState.getStats();
 
        return {
            jobCount: jobStats.itemCount,
            maxJobs: jobStats.maxItems,
            oldestJobId: jobStats.oldestKey as number | null,
            newestJobId: jobStats.newestKey as number | null,
            jobIds: jobStats.keys as number[],
            generatedCodeCount: generatedCodeStats.itemCount,
            generatedCodeJobIds: generatedCodeStats.keys as number[],
            nodeIndexCount: nodeIndexStats.itemCount,
            nodeIndexJobIds: nodeIndexStats.keys as number[],
            mappingHashCount: mappingHashStats.itemCount,
            mappingHashJobIds: mappingHashStats.keys as number[],
        };
    }
}