|
| 1 | +import Vapor |
| 2 | +import OpenAPIRuntime |
| 3 | + |
| 4 | +enum Streaming { |
| 5 | + |
| 6 | +#if compiler(>=5.9) |
| 7 | + @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) |
| 8 | + actor Writer { |
| 9 | + let unownedExecutor: UnownedSerialExecutor |
| 10 | + let writer: any Vapor.BodyStreamWriter |
| 11 | + let body: OpenAPIRuntime.HTTPBody |
| 12 | + |
| 13 | + init( |
| 14 | + writer: any Vapor.BodyStreamWriter, |
| 15 | + body: OpenAPIRuntime.HTTPBody |
| 16 | + ) { |
| 17 | + self.unownedExecutor = writer.eventLoop.executor.asUnownedSerialExecutor() |
| 18 | + self.writer = writer |
| 19 | + self.body = body |
| 20 | + } |
| 21 | + |
| 22 | + func write() async { |
| 23 | + do { |
| 24 | + for try await chunk in body { |
| 25 | + try await writer.write(.buffer(ByteBuffer(bytes: chunk))).get() |
| 26 | + } |
| 27 | + try await writer.write(.end).get() |
| 28 | + } catch { |
| 29 | + try? await writer.write(.error(error)).get() |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | +#endif // compiler(>=5.9) |
| 34 | + |
| 35 | + static func write( |
| 36 | + body: OpenAPIRuntime.HTTPBody, |
| 37 | + writer: any Vapor.BodyStreamWriter |
| 38 | + ) async { |
| 39 | +#if compiler(>=5.9) |
| 40 | + if #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) { |
| 41 | + await Writer(writer: writer, body: body).write() |
| 42 | + return |
| 43 | + } |
| 44 | +#endif // compiler(>=5.9) |
| 45 | + await _writeWithHops(body: body, writer: writer) |
| 46 | + } |
| 47 | + |
| 48 | + static func _writeWithHops( |
| 49 | + body: OpenAPIRuntime.HTTPBody, |
| 50 | + writer: any Vapor.BodyStreamWriter |
| 51 | + ) async { |
| 52 | + do { |
| 53 | + for try await chunk in body { |
| 54 | + try await writer.eventLoop.flatSubmit { |
| 55 | + writer.write(.buffer(ByteBuffer(bytes: chunk))) |
| 56 | + }.get() |
| 57 | + } |
| 58 | + try await writer.eventLoop.flatSubmit { |
| 59 | + writer.write(.end) |
| 60 | + }.get() |
| 61 | + } catch { |
| 62 | + try? await writer.eventLoop.flatSubmit { |
| 63 | + writer.write(.error(error)) |
| 64 | + }.get() |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments