Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LOAD-Synchronisation umgeschrieben #21

Merged
merged 2 commits into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 32 additions & 20 deletions lvp.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,23 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

// To run this code type `jshell -R-ea --enable-preview`

enum SSEType { WRITE, CALL, SCRIPT, LOAD, CLEAR; }
Expand All @@ -31,16 +32,19 @@ class LiveView {
final int port;
static int defaultPort = 50_001;
static final String index = "./web/index.html";
static Map<Integer,LiveView> views = new HashMap<>();
static Map<Integer,LiveView> views = new ConcurrentHashMap<>();
List<String> paths = new ArrayList<>();

static void setDefaultPort(int port) { defaultPort = port != 0 ? Math.abs(port) : 50_001; }
static int getDefaultPort() { return defaultPort; }

List<HttpExchange> sseClientConnections;

// barrier required to temporarily block SSE event of type `SSEType.LOAD`
private final CyclicBarrier barrier = new CyclicBarrier(2);
// lock required to temporarily block processing of `SSEType.LOAD`
Lock lock = new ReentrantLock();
Condition loadEventOccurredCondition = lock.newCondition();
boolean loadEventOccured = false;


static LiveView onPort(int port) {
port = Math.abs(port);
Expand All @@ -64,18 +68,20 @@ private LiveView(int port) throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", port), 0);
System.out.println("Open http://localhost:" + port + " in your browser");

// loaded-Request to signal successful processing of SSEType.LOAD
server.createContext("/loaded", exchange -> {
if (!exchange.getRequestMethod().equalsIgnoreCase("post")) {
exchange.sendResponseHeaders(405, -1); // Method Not Allowed
return;
}
exchange.sendResponseHeaders(200, 0);
exchange.close();
try {
barrier.await(2L, TimeUnit.SECONDS);
} catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
System.err.print(e);
System.exit(1);
lock.lock();
try { // try/finally pattern for locks
loadEventOccured = true;
loadEventOccurredCondition.signalAll();
} finally {
lock.unlock();
}
});

Expand Down Expand Up @@ -118,21 +124,27 @@ private LiveView(int port) throws IOException {
void sendServerEvent(SSEType sseType, String data) {
List<HttpExchange> deadConnections = new ArrayList<>();
for (HttpExchange connection : sseClientConnections) {
if (sseType == SSEType.LOAD) lock.lock();
try {
connection.getResponseBody()
.write(("data: " + (sseType + ":" + data).replaceAll("(\\r|\\n|\\r\\n)", "\\\\n") + "\n\n")
.getBytes(StandardCharsets.UTF_8));
connection.getResponseBody().flush();
if (sseType == SSEType.LOAD) {
try {
barrier.await(2L, TimeUnit.SECONDS);
} catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
System.err.print(SSEType.LOAD + " missed confirmation: " + e);
deadConnections.add(connection); // connection is assumed to be dead
}
if (sseType == SSEType.LOAD && !loadEventOccured) {
loadEventOccurredCondition.await(2_000, TimeUnit.MILLISECONDS);
if (!loadEventOccured)
System.err.println("LOAD-Timeout: " + data);
// TODO: failed load i.e. <script>-Tag should be removed in index.html
}
} catch (IOException e) {
deadConnections.add(connection);
} catch (InterruptedException e) {
System.err.println("LOAD-Timeout: " + data + ", " + e);
} finally {
if (sseType == SSEType.LOAD) {
loadEventOccured = false;
lock.unlock();
}
}
}
sseClientConnections.removeAll(deadConnections);
Expand Down
4 changes: 1 addition & 3 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
<meta charset="UTF-8">
<link href="web/favicon.ico" rel="icon" type="image/x-icon" />
<title>Clerk in Java Prototype</title>
<link rel="stylesheet" href="web/clerk.css">

<!-- <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js" defer></script> -->
<link rel="stylesheet" href="web/clerk.css">
<script src="web/script.js" defer></script>
</head>
<body>
Expand Down