func runAction()

in backpressure-file-io-channel/Sources/BackpressureChannelToFileIO/SaveEverythingHTTPServer.swift [48:91]


    func runAction(_ action: FileIOCoordinatorState.Action, context: ChannelHandlerContext) {
        self.logger.trace("doing action \(action)")
        switch action.main {
        case .closeFile(let fileHandle):
            try! fileHandle.close()
        case .processingCompletedDiscardResources(let fileHandle, let maybeError):
            try! fileHandle?.close()
            self.logger.debug("fully handled request: \(maybeError.debugDescription)")
            self.requestFullyProcessed(context: context, result: maybeError.map { .failure($0) } ?? .success(()))
        case .openFile(let path):
            self.fileIO.openFile(path: path,
                                 mode: .write,
                                 flags: .allowFileCreation(posixMode: 0o600),
                                 eventLoop: context.eventLoop).flatMap { fileHandle in
                        self.fileIO.changeFileSize(fileHandle: fileHandle,
                                                   size: 0,
                                                   eventLoop: context.eventLoop).map { fileHandle }
            }.whenComplete { result in
                switch result {
                case .success(let fileHandle):
                    self.runAction(self.state.didOpenTargetFile(fileHandle),
                                   context: context)
                case .failure(let error):
                    self.runAction(self.state.didError(error),
                                   context: context)
                }
            }
        case .nothingWeAreWaiting:
            ()
        case .startWritingToTargetFile:
            let (fileHandle, bytes) = self.state.pullNextChunkToWrite()
            self.fileIO.write(fileHandle: fileHandle, buffer: bytes, eventLoop: context.eventLoop).whenComplete { result in
                switch result {
                case .success(()):
                    self.runAction(self.state.didFinishWritingOneChunkToFile(), context: context)
                case .failure(let error):
                    self.runAction(self.state.didError(error), context: context)
                }
            }
        }
        if action.callRead {
            context.read()
        }
    }