forked from polis-vk/2024-highload-dht
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyServer.java
178 lines (149 loc) · 5.99 KB
/
MyServer.java
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
package ru.vk.itmo.test.tarazanovmaxim;
import one.nio.http.HttpServer;
import one.nio.http.HttpServerConfig;
import one.nio.http.HttpSession;
import one.nio.http.Param;
import one.nio.http.Path;
import one.nio.http.Request;
import one.nio.http.RequestMethod;
import one.nio.http.Response;
import one.nio.server.AcceptorConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vk.itmo.ServiceConfig;
import ru.vk.itmo.dao.BaseEntry;
import ru.vk.itmo.dao.Config;
import ru.vk.itmo.dao.Entry;
import ru.vk.itmo.test.tarazanovmaxim.dao.ReferenceDao;
import java.io.IOException;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
public class MyServer extends HttpServer {
private final ReferenceDao dao;
private static final long FLUSH_THRESHOLD_BYTES = 1 << 20;
private static final String PATH = "/v0/entity";
private static final long REQUEST_TTL = TimeUnit.SECONDS.toNanos(100);
private final ExecutorService executorService;
private static final Logger logger = LoggerFactory.getLogger(MyServer.class);
public MyServer(ServiceConfig config) throws IOException {
super(createServerConfig(config));
dao = new ReferenceDao(new Config(config.workingDir(), FLUSH_THRESHOLD_BYTES));
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() / 2 + 1);
}
private static HttpServerConfig createServerConfig(ServiceConfig serviceConfig) {
HttpServerConfig httpServerConfig = new HttpServerConfig();
AcceptorConfig acceptorConfig = new AcceptorConfig();
acceptorConfig.port = serviceConfig.selfPort();
acceptorConfig.reusePort = true;
httpServerConfig.acceptors = new AcceptorConfig[]{acceptorConfig};
httpServerConfig.closeSessions = true;
return httpServerConfig;
}
private static MemorySegment toMemorySegment(String string) {
return MemorySegment.ofArray(string.getBytes(StandardCharsets.UTF_8));
}
public void close() {
executorService.close();
try {
dao.close();
} catch (IOException e) {
logger.error("IOException in close()->dao.close()");
throw new RuntimeException(e);
}
}
@Path(PATH)
@RequestMethod(Request.METHOD_GET)
public final Response get(@Param(value = "id", required = true) String id) {
MemorySegment key =
(id == null || id.isEmpty())
? null
: toMemorySegment(id);
if (key == null) {
return new Response(Response.BAD_REQUEST, Response.EMPTY);
}
Entry<MemorySegment> entry = dao.get(key);
if (entry == null) {
return new Response(Response.NOT_FOUND, Response.EMPTY);
}
return Response.ok(entry.value().toArray(ValueLayout.JAVA_BYTE));
}
@Path(PATH)
@RequestMethod(Request.METHOD_PUT)
public final Response put(@Param(value = "id", required = true) String id, Request request) {
MemorySegment key =
(id == null || id.isEmpty())
? null
: toMemorySegment(id);
if (key == null) {
return new Response(Response.BAD_REQUEST, Response.EMPTY);
}
Entry<MemorySegment> entry = new BaseEntry<>(
key,
MemorySegment.ofArray(request.getBody())
);
dao.upsert(entry);
return new Response(Response.CREATED, Response.EMPTY);
}
@Path(PATH)
@RequestMethod(Request.METHOD_DELETE)
public final Response delete(@Param(value = "id", required = true) String id) {
MemorySegment key =
(id == null || id.isEmpty())
? null
: toMemorySegment(id);
if (key == null) {
return new Response(Response.BAD_REQUEST, Response.EMPTY);
}
dao.upsert(new BaseEntry<>(key, null));
return new Response(Response.ACCEPTED, Response.EMPTY);
}
@Path(PATH)
public Response otherMethod() {
return new Response(Response.METHOD_NOT_ALLOWED, Response.EMPTY);
}
@Override
public void handleDefault(Request request, HttpSession session) {
Response response = new Response(Response.BAD_REQUEST, Response.EMPTY);
sendResponse(response, session);
}
@Override
public void handleRequest(Request request, HttpSession session) {
try {
long startTime = System.nanoTime();
executorService.execute(() -> {
if (System.nanoTime() > startTime + REQUEST_TTL) {
sendResponse(new Response(Response.REQUEST_TIMEOUT, Response.EMPTY), session);
return;
}
try {
super.handleRequest(request, session);
} catch (Exception e) {
logger.error("IOException in handleRequest->executorService.execute()");
System.out.println(e.getClass());
sendResponse(
new Response(
e.getClass() == IOException.class ? Response.INTERNAL_ERROR : Response.BAD_REQUEST,
Response.EMPTY
),
session
);
}
});
} catch (RejectedExecutionException e) {
logger.error("RejectedExecutionException in handleRequest: " + request + session);
sendResponse(new Response("429 Too Many Requests", Response.EMPTY), session);
}
}
public void sendResponse(Response response, HttpSession session) {
try {
session.sendResponse(response);
} catch (IOException e) {
logger.error("IOException in sendResponse: " + response + session);
}
}
}