MCPcopy Create free account
hub / github.com/fastify/fastify / sendWebStream

Function sendWebStream

lib/reply.js:748–819  ·  view source on GitHub ↗
(payload, res, reply)

Source from the content-addressed store, hash-verified

746}
747
748function sendWebStream (payload, res, reply) {
749 if (payload.locked) {
750 throw new FST_ERR_REP_READABLE_STREAM_LOCKED()
751 }
752
753 let sourceOpen = true
754 let errorLogged = false
755 let waitingDrain = false
756 const reader = payload.getReader()
757
758 eos(res, function (err) {
759 if (sourceOpen) {
760 if (err != null && res.headersSent && !errorLogged) {
761 errorLogged = true
762 logStreamError(err, reply, res)
763 }
764 reader.cancel().catch(noop)
765 }
766 })
767
768 if (!res.headersSent) {
769 for (const key in reply[kReplyHeaders]) {
770 res.setHeader(key, reply[kReplyHeaders][key])
771 }
772 } else {
773 reply.log.warn('response will send, but you shouldn\'t use res.writeHead in stream mode')
774 }
775
776 function onRead (result) {
777 if (result.done) {
778 sourceOpen = false
779 sendTrailer(null, res, reply)
780 return
781 }
782 /* c8 ignore next 5 - race condition: eos handler typically fires first */
783 if (res.destroyed) {
784 sourceOpen = false
785 reader.cancel().catch(noop)
786 return
787 }
788 const shouldContinue = res.write(result.value)
789 if (shouldContinue === false) {
790 waitingDrain = true
791 res.once('drain', onDrain)
792 return
793 }
794 reader.read().then(onRead, onReadError)
795 }
796
797 function onDrain () {
798 if (!waitingDrain || !sourceOpen || res.destroyed) {
799 return
800 }
801 waitingDrain = false
802 reader.read().then(onRead, onReadError)
803 }
804
805 function onReadError (err) {

Callers 1

onSendEndFunction · 0.85

Calls 3

logStreamErrorFunction · 0.85
warnMethod · 0.80
thenMethod · 0.80

Tested by

no test coverage detected