File size: 6,751 Bytes
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package demo;

// Codex-authored reviewed reference implementation, not a model-generation receipt.
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

public final class App {
    private static final MathContext MC = MathContext.DECIMAL128;
    private static final BigDecimal MAX = new BigDecimal("1e24");
    private static final class Failure extends RuntimeException {
        final int status;
        Failure(String code, int status) { super(code); this.status = status; }
    }
    private static Failure invalid() { return new Failure("INVALID_EXPRESSION", 400); }
    private static Failure limit() { return new Failure("LIMIT_EXCEEDED", 422); }
    private static BigDecimal bounded(BigDecimal value) {
        if (value.abs().compareTo(MAX) > 0) throw limit();
        return value;
    }
    private static final class Parser {
        final String text;
        int cursor, operators, depth;
        Parser(String text) { this.text = text; }
        void spaces() { while (cursor < text.length() && text.charAt(cursor) == ' ') cursor++; }
        boolean take(char token) {
            spaces();
            if (cursor < text.length() && text.charAt(cursor) == token) { cursor++; return true; }
            return false;
        }
        void operator() { if (++operators > 64) throw limit(); }
        BigDecimal sum() {
            BigDecimal value = product();
            while (true) {
                if (take('+')) { operator(); value = bounded(value.add(product(), MC)); }
                else if (take('-')) { operator(); value = bounded(value.subtract(product(), MC)); }
                else return value;
            }
        }
        BigDecimal product() {
            BigDecimal value = unary();
            while (true) {
                if (take('*')) { operator(); value = bounded(value.multiply(unary(), MC)); }
                else if (take('/')) {
                    operator(); BigDecimal divisor = unary();
                    if (divisor.signum() == 0) throw new Failure("DIVISION_BY_ZERO", 400);
                    value = bounded(value.divide(divisor, MC));
                } else return value;
            }
        }
        BigDecimal unary() {
            boolean negative = false;
            while (true) {
                if (take('+')) operator();
                else if (take('-')) { operator(); negative = !negative; }
                else break;
            }
            BigDecimal value;
            if (take('(')) {
                if (++depth > 16) throw limit();
                value = sum();
                if (!take(')')) throw invalid();
                depth--;
            } else value = number();
            return negative ? value.negate() : value;
        }
        BigDecimal number() {
            spaces(); int start = cursor, digits = 0;
            while (cursor < text.length() && Character.isDigit(text.charAt(cursor))) { cursor++; digits++; }
            if (cursor < text.length() && text.charAt(cursor) == '.') {
                cursor++; int fractionStart = cursor;
                while (cursor < text.length() && Character.isDigit(text.charAt(cursor))) { cursor++; digits++; }
                if (cursor == fractionStart) throw invalid();
            }
            if (digits == 0) throw invalid();
            if (digits > 24) throw limit();
            return bounded(new BigDecimal(text.substring(start, cursor)));
        }
        String calculate() {
            if (text.length() > 128) throw limit();
            if (text.isBlank() || !text.matches("[0-9+*/(). -]+")) throw invalid();
            BigDecimal value = sum(); spaces();
            if (cursor != text.length()) throw invalid();
            value = value.setScale(12, RoundingMode.HALF_UP).stripTrailingZeros();
            return value.signum() == 0 ? "0" : value.toPlainString();
        }
    }
    private static String expression(HttpExchange exchange) {
        String query = exchange.getRequestURI().getRawQuery();
        if (query == null || !query.startsWith("expression64=")) throw new Failure("INVALID_INPUT", 400);
        String encoded = query.substring(13);
        if (encoded.length() > 256 || !encoded.matches("[A-Za-z0-9_-]+")) throw new Failure("INVALID_INPUT", 400);
        try {
            byte[] bytes = Base64.getUrlDecoder().decode(encoded);
            String decoded = new String(bytes, StandardCharsets.UTF_8);
            if (!Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).equals(encoded)
                    || !Arrays.equals(bytes, decoded.getBytes(StandardCharsets.UTF_8)))
                throw new IllegalArgumentException();
            return decoded;
        } catch (IllegalArgumentException error) { throw new Failure("INVALID_INPUT", 400); }
    }
    private static void send(HttpExchange exchange, int status, String json) throws IOException {
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
        exchange.getResponseHeaders().set("Cache-Control", "no-store");
        exchange.sendResponseHeaders(status, bytes.length);
        try (var output = exchange.getResponseBody()) { output.write(bytes); }
    }
    private static void handle(HttpExchange exchange) throws IOException {
        try {
            String path = exchange.getRequestURI().getRawPath();
            if (!path.equals("/health") && !path.equals("/api/calculate")) throw new Failure("NOT_FOUND", 404);
            if (!exchange.getRequestMethod().equals("GET")) throw new Failure("METHOD_NOT_ALLOWED", 405);
            if (path.equals("/health")) { send(exchange, 200, "{\"status\":\"ok\"}"); return; }
            if (!"Bearer demo-calculator".equals(exchange.getRequestHeaders().getFirst("Authorization")))
                throw new Failure("UNAUTHORIZED", 401);
            String text = expression(exchange), result = new Parser(text).calculate();
            send(exchange, 200, "{\"expression\":\"" + text + "\",\"result\":\"" + result + "\"}");
        } catch (Failure failure) { send(exchange, failure.status, "{\"error\":\"" + failure.getMessage() + "\"}"); }
        finally { exchange.close(); }
    }
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 32);
        server.createContext("/", App::handle);
        server.setExecutor(null);
        server.start();
    }
}