You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.8 KiB
53 lines
1.8 KiB
import LifecycleUnit from '../lifecycle/Unit.ts'
|
|
import {Unit} from '../lifecycle/decorators.ts'
|
|
import Kernel from '../http/kernel/Kernel.ts'
|
|
import {Logging} from '../service/logging/Logging.ts'
|
|
import {serve} from '../external/http.ts'
|
|
import {Request} from '../http/Request.ts'
|
|
import {withTimeout} from '../support/timeout.ts'
|
|
import {http} from '../http/response/helpers.ts'
|
|
import {HTTPStatus} from '../const/http.ts'
|
|
import Config from './Config.ts'
|
|
|
|
/**
|
|
* Lifecycle unit which starts the HTTP server.
|
|
* @extends LifecycleUnit
|
|
*/
|
|
@Unit()
|
|
export default class HttpServer extends LifecycleUnit {
|
|
protected _server: any // TODO replace with more specific type
|
|
|
|
constructor(
|
|
protected readonly kernel: Kernel,
|
|
protected readonly config: Config,
|
|
protected readonly logger: Logging,
|
|
) {
|
|
super()
|
|
}
|
|
|
|
public async up() {
|
|
this._server = serve({ port: 8000 })
|
|
this.logger.success(`HTTP/S server listening on port 8000!`)
|
|
|
|
const request_timeout: number = this.config.get('server.request_timeout', 15000)
|
|
|
|
for await ( const native_request of this._server ) {
|
|
let req: Request = this.make(Request, native_request)
|
|
|
|
await withTimeout(request_timeout, this.kernel.handle(req))
|
|
.on_time(output_req => {
|
|
output_req.response.send()
|
|
})
|
|
.late(output_req => {
|
|
this.logger.error(`Request timed out. Response was already sent on path: ${req.path}. Consider increasing server.request_timeout.`)
|
|
})
|
|
.timeout(async () => {
|
|
const factory = http(HTTPStatus.REQUEST_TIMEOUT)
|
|
const output_req = await factory.write(req)
|
|
output_req.response.send()
|
|
})
|
|
.run()
|
|
}
|
|
}
|
|
}
|