Initialize standalone EzServer for macOS
This commit is contained in:
commit
cf192a5f3c
11 files changed
+680
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
|
||||
package struct PatientRecord: Codable, Identifiable {
|
||||
package let id: UUID
|
||||
package var name: String
|
||||
package var chartNumber: String
|
||||
package var images: [PatientImage]
|
||||
|
||||
package init(id: UUID, name: String, chartNumber: String) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.chartNumber = chartNumber
|
||||
self.images = []
|
||||
}
|
||||
}
|
||||
|
||||
package struct PatientImage: Codable, Identifiable {
|
||||
package let id: UUID
|
||||
package let name: String
|
||||
package let importedAt: Date
|
||||
package var dicomCount: Int?
|
||||
|
||||
package init(id: UUID, name: String, importedAt: Date, dicomCount: Int? = nil) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.importedAt = importedAt
|
||||
self.dicomCount = dicomCount
|
||||
}
|
||||
}
|
||||
|
||||
package enum LibraryPaths {
|
||||
package static let index = "patients.json"
|
||||
|
||||
package static func attachment(_ id: UUID, in directory: URL) -> URL {
|
||||
directory.appendingPathComponent(id.uuidString)
|
||||
}
|
||||
|
||||
package static func slice(_ number: Int, of id: UUID, in directory: URL) -> URL {
|
||||
attachment(id, in: directory).appendingPathComponent("slice-\(number).dcm")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import CryptoKit
|
||||
import EzDentStorage
|
||||
import Foundation
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct LibraryAPI {
|
||||
struct Listing: Encodable {
|
||||
let patients: [PatientSummary]
|
||||
let total: Int
|
||||
let offset: Int
|
||||
let limit: Int
|
||||
}
|
||||
|
||||
struct PatientSummary: Encodable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let chartNumber: String
|
||||
let imageCount: Int
|
||||
|
||||
init(_ patient: PatientRecord) {
|
||||
id = patient.id
|
||||
name = patient.name
|
||||
chartNumber = patient.chartNumber
|
||||
imageCount = patient.images.count
|
||||
}
|
||||
}
|
||||
|
||||
struct File {
|
||||
let handle: FileHandle
|
||||
let bytes: Int
|
||||
let contentType: String
|
||||
let filename: String
|
||||
}
|
||||
|
||||
enum Result {
|
||||
case listing(Listing)
|
||||
case patient(PatientRecord)
|
||||
case file(File)
|
||||
case invalidRequest
|
||||
case unauthorized
|
||||
case notFound
|
||||
case unavailable
|
||||
}
|
||||
|
||||
private let directory: URL
|
||||
private let token: SHA256.Digest
|
||||
|
||||
init?(environment: [String: String]) throws {
|
||||
let path = environment["EZSERVER_LIBRARY"]
|
||||
let secret = environment["EZSERVER_TOKEN"]
|
||||
guard path != nil || secret != nil else { return nil }
|
||||
guard let path, path.hasPrefix("/"), let secret, secret.utf8.count >= 32,
|
||||
secret.utf8.allSatisfy({ (33...126).contains($0) }) else {
|
||||
throw ConfigurationError.incomplete
|
||||
}
|
||||
|
||||
let directory = URL(fileURLWithPath: path, isDirectory: true).resolvingSymlinksInPath()
|
||||
let index = directory.appendingPathComponent(LibraryPaths.index)
|
||||
guard (try? index.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]))
|
||||
.map({ $0.isRegularFile == true && $0.isSymbolicLink != true }) == true else {
|
||||
throw ConfigurationError.invalidIndex
|
||||
}
|
||||
self.directory = directory
|
||||
token = SHA256.hash(data: Data(secret.utf8))
|
||||
}
|
||||
|
||||
func response(path: [String], query: [URLQueryItem], authorization: String?) -> Result {
|
||||
guard let authorization, authorization.hasPrefix("Bearer ") else { return .unauthorized }
|
||||
let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8))
|
||||
let mismatch = zip(candidate, token).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) }
|
||||
guard mismatch == 0 else { return .unauthorized }
|
||||
|
||||
guard let index = try? openFile(directory.appendingPathComponent(LibraryPaths.index)) else {
|
||||
return .unavailable
|
||||
}
|
||||
do {
|
||||
defer { try? index.handle.close() }
|
||||
guard index.bytes <= 32 * 1024 * 1024 else { return .unavailable }
|
||||
let data = try index.handle.readToEnd() ?? Data()
|
||||
let patients = try JSONDecoder().decode([PatientRecord].self, from: data)
|
||||
|
||||
if path.isEmpty { return list(patients, query: query) }
|
||||
guard let patientID = UUID(uuidString: path[0]),
|
||||
let patient = patients.first(where: { $0.id == patientID }) else { return .notFound }
|
||||
if path.count == 1 { return .patient(patient) }
|
||||
|
||||
guard path.count == 3 || path.count == 5, path[1] == "images",
|
||||
let imageID = UUID(uuidString: path[2]),
|
||||
let image = patient.images.first(where: { $0.id == imageID }) else { return .notFound }
|
||||
if path.count == 3, image.dicomCount == nil {
|
||||
return .file(try openFile(LibraryPaths.attachment(image.id, in: directory),
|
||||
filename: image.name))
|
||||
}
|
||||
if path.count == 5, path[3] == "slices", let number = Int(path[4]),
|
||||
let count = image.dicomCount, (1...4096).contains(count), (1...count).contains(number) {
|
||||
return .file(try openFile(LibraryPaths.slice(number, of: image.id, in: directory),
|
||||
filename: "slice-\(number).dcm", contentType: "application/dicom"))
|
||||
}
|
||||
return .notFound
|
||||
} catch FileError.notFound {
|
||||
return .notFound
|
||||
} catch {
|
||||
return .unavailable
|
||||
}
|
||||
}
|
||||
|
||||
private func list(_ patients: [PatientRecord], query: [URLQueryItem]) -> Result {
|
||||
let search = query.first { $0.name == "q" }?.value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let offset = query.first { $0.name == "offset" }?.value ?? "0"
|
||||
let limit = query.first { $0.name == "limit" }?.value ?? "50"
|
||||
guard let offset = Int(offset), offset >= 0, let limit = Int(limit),
|
||||
(1...200).contains(limit), search.count <= 200 else { return .invalidRequest }
|
||||
let selected = patients.filter {
|
||||
search.isEmpty || $0.name.localizedStandardContains(search)
|
||||
|| $0.chartNumber.localizedStandardContains(search)
|
||||
}
|
||||
let start = min(offset, selected.count)
|
||||
let results = selected.dropFirst(start).prefix(limit).map(PatientSummary.init)
|
||||
return .listing(Listing(patients: results, total: selected.count, offset: offset, limit: limit))
|
||||
}
|
||||
|
||||
private func openFile(_ url: URL, filename: String = "", contentType: String? = nil) throws -> File {
|
||||
guard url.deletingLastPathComponent().resolvingSymlinksInPath().path
|
||||
== url.deletingLastPathComponent().path else { throw FileError.notFound }
|
||||
let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
|
||||
guard descriptor >= 0 else { throw FileError.notFound }
|
||||
var metadata = stat()
|
||||
guard fstat(descriptor, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG else {
|
||||
close(descriptor)
|
||||
throw FileError.notFound
|
||||
}
|
||||
let mime = UTType(filenameExtension: (filename as NSString).pathExtension)?.preferredMIMEType
|
||||
return File(handle: FileHandle(fileDescriptor: descriptor, closeOnDealloc: true),
|
||||
bytes: Int(metadata.st_size), contentType: contentType ?? mime ?? "application/octet-stream",
|
||||
filename: filename)
|
||||
}
|
||||
|
||||
private enum ConfigurationError: LocalizedError {
|
||||
case incomplete, invalidIndex
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .incomplete: return "Set EZSERVER_LIBRARY to an absolute path and EZSERVER_TOKEN to at least 32 printable ASCII characters."
|
||||
case .invalidIndex: return "EZSERVER_LIBRARY must contain an EzDent patients.json index."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum FileError: Error { case notFound }
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import Foundation
|
||||
import Network
|
||||
|
||||
private struct APIVersion: Encodable {
|
||||
let name: String
|
||||
let url: String
|
||||
let supportStatus: String
|
||||
}
|
||||
|
||||
private struct VersionList: Encodable {
|
||||
let errorCode = 0
|
||||
let serverName = "EzWebServer"
|
||||
let currentVersionName = "3.0.6"
|
||||
let currentStageVersionName = "0"
|
||||
let versions: [APIVersion]
|
||||
}
|
||||
|
||||
private struct VersionMatch: Encodable {
|
||||
let errorCode = 0
|
||||
let serverName = "EzWebServer"
|
||||
let clientVersion: APIVersion
|
||||
let serverVersion: APIVersion
|
||||
}
|
||||
|
||||
private final class LocalServer {
|
||||
private let listener: NWListener
|
||||
private let queue = DispatchQueue(label: "ezserver.loopback")
|
||||
private let maxHeaderSize = 8192
|
||||
private let library: LibraryAPI?
|
||||
|
||||
init(port: UInt16, library: LibraryAPI?) throws {
|
||||
self.library = library
|
||||
let parameters = NWParameters.tcp
|
||||
parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!)
|
||||
listener = try NWListener(using: parameters)
|
||||
}
|
||||
|
||||
func start() {
|
||||
listener.stateUpdateHandler = { state in
|
||||
switch state {
|
||||
case .ready:
|
||||
if let port = self.listener.port {
|
||||
print("EzServer Mac is listening on http://127.0.0.1:\(port)")
|
||||
fflush(stdout)
|
||||
}
|
||||
case let .failed(error):
|
||||
FileHandle.standardError.write(Data("Could not start EzServer: \(error)\n".utf8))
|
||||
exit(EXIT_FAILURE)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
listener.newConnectionHandler = { [weak self] connection in
|
||||
guard let self else { connection.cancel(); return }
|
||||
connection.start(queue: self.queue)
|
||||
let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() }
|
||||
self.queue.asyncAfter(deadline: .now() + 5, execute: timeout)
|
||||
self.receive(on: connection, buffer: Data(), timeout: timeout)
|
||||
}
|
||||
listener.start(queue: queue)
|
||||
}
|
||||
|
||||
private func receive(on connection: NWConnection, buffer: Data, timeout: DispatchWorkItem) {
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: maxHeaderSize - buffer.count) {
|
||||
[weak self] data, _, complete, failure in
|
||||
guard let self, failure == nil else { connection.cancel(); return }
|
||||
var request = buffer
|
||||
if let data { request.append(data) }
|
||||
if let boundary = request.range(of: Data("\r\n\r\n".utf8)) {
|
||||
timeout.cancel()
|
||||
self.handle(request.prefix(upTo: boundary.lowerBound), on: connection)
|
||||
} else if request.count >= self.maxHeaderSize {
|
||||
self.send(["error": "Request header too large"], status: "431 Request Header Fields Too Large", on: connection)
|
||||
} else if complete {
|
||||
connection.cancel()
|
||||
} else {
|
||||
self.receive(on: connection, buffer: request, timeout: timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ request: Data, on connection: NWConnection) {
|
||||
let lines = String(decoding: request, as: UTF8.self).components(separatedBy: "\r\n")
|
||||
let requestLine = lines[0].split(separator: " ", omittingEmptySubsequences: false)
|
||||
let hosts = lines.dropFirst().compactMap { line -> String? in
|
||||
let parts = line.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false)
|
||||
guard parts.count == 2, parts[0].lowercased() == "host" else { return nil }
|
||||
return parts[1].trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
guard requestLine.count == 3, ["HTTP/1.0", "HTTP/1.1"].contains(requestLine[2]),
|
||||
requestLine[1].hasPrefix("/"), !requestLine[1].hasPrefix("//"),
|
||||
let target = URLComponents(string: String(requestLine[1])),
|
||||
hosts.count == 1,
|
||||
hosts[0].range(of: #"\A(?:127\.0\.0\.1|localhost)(?::[0-9]{1,5})?\z"#,
|
||||
options: [.regularExpression, .caseInsensitive]) != nil else {
|
||||
send(["error": "Invalid request or host"], status: "400 Bad Request", on: connection)
|
||||
return
|
||||
}
|
||||
guard requestLine[0] == "GET" else {
|
||||
send(["error": "Only GET is supported"], status: "405 Method Not Allowed",
|
||||
extraHeaders: "Allow: GET\r\n", on: connection)
|
||||
return
|
||||
}
|
||||
|
||||
let segments = target.path.split(separator: "/").map(String.init)
|
||||
if segments.starts(with: ["mac", "v1", "patients"]) {
|
||||
let authorization = lines.dropFirst().compactMap { line -> String? in
|
||||
let fields = line.split(separator: ":", maxSplits: 1)
|
||||
guard fields.count == 2, fields[0].lowercased() == "authorization" else { return nil }
|
||||
return fields[1].trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
serveLibrary(path: Array(segments.dropFirst(3)), query: target.queryItems ?? [],
|
||||
authorization: authorization.count == 1 ? authorization[0] : nil, on: connection)
|
||||
return
|
||||
}
|
||||
|
||||
let apiURL = "http://\(hosts[0])/api/v1"
|
||||
let versions = [
|
||||
"1.0.0", "1.0.1", "1.1.0", "1.2.0", "1.3.0", "1.3.1", "1.3.2", "2.0.0",
|
||||
"3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6"
|
||||
].map { APIVersion(name: $0, url: apiURL, supportStatus: "supported") }
|
||||
let listing = VersionList(versions: versions)
|
||||
let path = target.path.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "/"))
|
||||
switch path {
|
||||
case "", "health":
|
||||
send(["service": "EzServer Mac", "status": "ok"], on: connection)
|
||||
case "api/v1/info/versions", "api/index.php/v1/info/versions":
|
||||
send(listing, on: connection)
|
||||
case "api/v1/info/versionsbyname", "api/index.php/v1/info/versionsbyname":
|
||||
let name = target.queryItems?.first(where: { $0.name == "name" })?.value ?? ""
|
||||
let match = versions.first { $0.name == name } ?? APIVersion(name: name, url: "", supportStatus: "unknown")
|
||||
send(VersionMatch(clientVersion: match, serverVersion: versions[versions.count - 1]), on: connection)
|
||||
default:
|
||||
send(["error": "Route is unavailable in the macOS preview"], status: "404 Not Found", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?,
|
||||
on connection: NWConnection) {
|
||||
guard let library else {
|
||||
send(["error": "Patient library is not configured"], status: "503 Service Unavailable", on: connection)
|
||||
return
|
||||
}
|
||||
switch library.response(path: path, query: query, authorization: authorization) {
|
||||
case let .listing(listing):
|
||||
send(listing, on: connection)
|
||||
case let .patient(patient):
|
||||
send(patient, on: connection)
|
||||
case let .file(file):
|
||||
let safeName = file.filename.addingPercentEncoding(withAllowedCharacters: CharacterSet(
|
||||
charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
|
||||
)) ?? "image"
|
||||
let headers = responseHeaders(status: "200 OK", type: file.contentType, bytes: file.bytes,
|
||||
extra: "Content-Disposition: attachment; filename*=UTF-8''\(safeName)\r\n")
|
||||
connection.send(content: headers, completion: .contentProcessed { [weak self] error in
|
||||
guard let self, error == nil else { connection.cancel(); return }
|
||||
self.stream(file.handle, remaining: file.bytes, on: connection)
|
||||
})
|
||||
case .unauthorized:
|
||||
send(["error": "Bearer token required"], status: "401 Unauthorized",
|
||||
extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection)
|
||||
case .invalidRequest:
|
||||
send(["error": "Invalid limit, offset or search query"], status: "400 Bad Request", on: connection)
|
||||
case .notFound:
|
||||
send(["error": "Patient or image not found"], status: "404 Not Found", on: connection)
|
||||
case .unavailable:
|
||||
send(["error": "Could not read patient library"], status: "503 Service Unavailable", on: connection)
|
||||
}
|
||||
}
|
||||
|
||||
private func stream(_ handle: FileHandle, remaining: Int, on connection: NWConnection) {
|
||||
guard remaining > 0,
|
||||
let chunk = try? handle.read(upToCount: min(remaining, 64 * 1024)),
|
||||
!chunk.isEmpty else {
|
||||
try? handle.close()
|
||||
connection.cancel()
|
||||
return
|
||||
}
|
||||
connection.send(content: chunk, completion: .contentProcessed { [weak self] error in
|
||||
guard let self, error == nil else {
|
||||
try? handle.close()
|
||||
connection.cancel()
|
||||
return
|
||||
}
|
||||
self.stream(handle, remaining: remaining - chunk.count, on: connection)
|
||||
})
|
||||
}
|
||||
|
||||
private func responseHeaders(status: String, type: String, bytes: Int, extra: String) -> Data {
|
||||
Data("HTTP/1.1 \(status)\r\nContent-Type: \(type)\r\nContent-Length: \(bytes)\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\(extra)\r\n".utf8)
|
||||
}
|
||||
|
||||
private func send<Response: Encodable>(_ response: Response, status: String = "200 OK",
|
||||
extraHeaders: String = "", on connection: NWConnection) {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .iso8601
|
||||
guard let body = try? encoder.encode(response) else { connection.cancel(); return }
|
||||
let headers = responseHeaders(status: status, type: "application/json; charset=utf-8",
|
||||
bytes: body.count, extra: extraHeaders)
|
||||
connection.send(content: headers + body, completion: .contentProcessed { _ in
|
||||
connection.cancel()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let servicePort = ProcessInfo.processInfo.environment["EZSERVER_PORT"] ?? "55005"
|
||||
guard let port = UInt16(servicePort), port > 0 else {
|
||||
FileHandle.standardError.write(Data("EZSERVER_PORT must be between 1 and 65535.\n".utf8))
|
||||
exit(EXIT_FAILURE)
|
||||
}
|
||||
do {
|
||||
let library = try LibraryAPI(environment: ProcessInfo.processInfo.environment)
|
||||
let server = try LocalServer(port: port, library: library)
|
||||
server.start()
|
||||
withExtendedLifetime(server) { dispatchMain() }
|
||||
} catch {
|
||||
FileHandle.standardError.write(Data("Could not start EzServer: \(error)\n".utf8))
|
||||
exit(EXIT_FAILURE)
|
||||
}
|
||||
Reference in new issue
Block a user