All Downloads are FREE. Search and download functionalities are using the official Maven repository.

software.amazon.smithy.lsp.DocumentLifecycleManager Maven / Gradle / Ivy

The newest version!
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

package software.amazon.smithy.lsp;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

/**
 * Tracks asynchronous lifecycle tasks and client-managed documents.
 * Allows cancelling of an ongoing task if a new task needs to be started.
 */
final class DocumentLifecycleManager {
    private static final Logger LOGGER = Logger.getLogger(DocumentLifecycleManager.class.getName());
    private final Map> tasks = new HashMap<>();
    private final Set managedDocumentUris = new HashSet<>();

    Set managedDocuments() {
        return managedDocumentUris;
    }

    boolean isManaged(String uri) {
        return managedDocuments().contains(uri);
    }

    CompletableFuture getTask(String uri) {
        return tasks.get(uri);
    }

    void cancelTask(String uri) {
        if (tasks.containsKey(uri)) {
            CompletableFuture task = tasks.get(uri);
            if (!task.isDone()) {
                task.cancel(true);
                tasks.remove(uri);
            }
        }
    }

    void putTask(String uri, CompletableFuture future) {
        tasks.put(uri, future);
    }

    void putOrComposeTask(String uri, CompletableFuture future) {
        if (tasks.containsKey(uri)) {
            tasks.computeIfPresent(uri, (k, v) -> v.thenCompose((unused) -> future));
        } else {
            tasks.put(uri, future);
        }
    }

    void cancelAllTasks() {
        for (CompletableFuture task : tasks.values()) {
            task.cancel(true);
        }
        tasks.clear();
    }

    void waitForAllTasks() throws ExecutionException, InterruptedException {
        for (CompletableFuture task : tasks.values()) {
            if (!task.isDone()) {
                task.get();
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy