package quic

import (
	
	
	
	

	
	
	
	
	
)

// A SendStream is a unidirectional Send Stream.
type SendStream struct {
	mutex sync.Mutex

	numOutstandingFrames int64 // outstanding STREAM and RESET_STREAM frames
	retransmissionQueue  []*wire.StreamFrame

	ctx       context.Context
	ctxCancel context.CancelCauseFunc

	streamID protocol.StreamID
	sender   streamSender

	// reliableSize is the portion of the stream that needs to be transmitted reliably,
	// even if the stream is cancelled.
	// This requires the peer to support RESET_STREAM_AT.
	// This value should not be accessed directly, but only through the reliableOffset method.
	// This method returns 0 if the peer doesn't support the RESET_STREAM_AT extension.
	reliableSize protocol.ByteCount
	writeOffset  protocol.ByteCount

	shutdownErr            error
	resetErr               *StreamError
	queuedResetStreamFrame *wire.ResetStreamFrame

	supportsResetStreamAt bool
	finishedWriting       bool // set once Close() is called
	finSent               bool // set when a STREAM_FRAME with FIN bit has been sent
	// Set when the application knows about the cancellation.
	// This can happen because the application called CancelWrite,
	// or because Write returned the error (for remote cancellations).
	cancellationFlagged bool
	completed           bool // set when this stream has been reported to the streamSender as completed

	dataForWriting []byte // during a Write() call, this slice is the part of p that still needs to be sent out
	nextFrame      *wire.StreamFrame

	writeChan chan struct{}
	writeOnce chan struct{}
	deadline  monotime.Time

	flowController flowcontrol.StreamFlowController
}

var (
	_ streamControlFrameGetter = &SendStream{}
	_ outgoingStream           = &SendStream{}
	_ sendStreamFrameHandler   = &SendStream{}
)

func newSendStream(
	 context.Context,
	 protocol.StreamID,
	 streamSender,
	 flowcontrol.StreamFlowController,
	 bool,
) *SendStream {
	 := &SendStream{
		streamID:              ,
		sender:                ,
		flowController:        ,
		writeChan:             make(chan struct{}, 1),
		writeOnce:             make(chan struct{}, 1), // cap: 1, to protect against concurrent use of Write
		supportsResetStreamAt: ,
	}
	.ctx, .ctxCancel = context.WithCancelCause()
	return 
}

// StreamID returns the stream ID.
func ( *SendStream) () StreamID {
	return .streamID // same for receiveStream and sendStream
}

// Write writes data to the stream.
// Write can be made to time out using [SendStream.SetWriteDeadline].
// If the stream was canceled, the error is a [StreamError].
func ( *SendStream) ( []byte) (int, error) {
	// Concurrent use of Write is not permitted (and doesn't make any sense),
	// but sometimes people do it anyway.
	// Make sure that we only execute one call at any given time to avoid hard to debug failures.
	.writeOnce <- struct{}{}
	defer func() { <-.writeOnce }()

	, ,  := .write()
	if  {
		.sender.onStreamCompleted(.streamID)
	}
	return , 
}

func ( *SendStream) ( []byte) (bool /* is newly completed */, int, error) {
	.mutex.Lock()
	defer .mutex.Unlock()

	if .resetErr != nil {
		.cancellationFlagged = true
		return .isNewlyCompleted(), 0, .resetErr
	}
	if .shutdownErr != nil {
		return false, 0, .shutdownErr
	}
	if .finishedWriting {
		return false, 0, fmt.Errorf("write on closed stream %d", .streamID)
	}
	if !.deadline.IsZero() && !monotime.Now().Before(.deadline) {
		return false, 0, errDeadline
	}
	if len() == 0 {
		return false, 0, nil
	}

	.dataForWriting = 

	var (
		  *time.Timer
		   int
		 bool
	)
	for {
		var  bool
		var  monotime.Time
		// As soon as dataForWriting becomes smaller than a certain size x, we copy all the data to a STREAM frame (s.nextFrame),
		// which can then be popped the next time we assemble a packet.
		// This allows us to return Write() when all data but x bytes have been sent out.
		// When the user now calls Close(), this is much more likely to happen before we popped that last STREAM frame,
		// allowing us to set the FIN bit on that frame (instead of sending an empty STREAM frame with FIN).
		if .canBufferStreamFrame() && len(.dataForWriting) > 0 {
			if .nextFrame == nil {
				 := wire.GetStreamFrame()
				.Offset = .writeOffset
				.StreamID = .streamID
				.DataLenPresent = true
				.Data = .Data[:len(.dataForWriting)]
				copy(.Data, .dataForWriting)
				.nextFrame = 
			} else {
				 := len(.nextFrame.Data)
				.nextFrame.Data = .nextFrame.Data[:+len(.dataForWriting)]
				copy(.nextFrame.Data[:], .dataForWriting)
			}
			.dataForWriting = nil
			 = len()
			 = true
		} else {
			 = len() - len(.dataForWriting)
			 = .deadline
			if !.IsZero() {
				if !monotime.Now().Before() {
					.dataForWriting = nil
					return false, , errDeadline
				}
				if  == nil {
					 = time.NewTimer(monotime.Until())
					defer .Stop()
				} else {
					.Reset(monotime.Until())
				}
			}
			if .dataForWriting == nil || .shutdownErr != nil || .resetErr != nil {
				break
			}
		}

		.mutex.Unlock()
		if ! {
			.sender.onHasStreamData(.streamID, ) // must be called without holding the mutex
			 = true
		}
		if  {
			.mutex.Lock()
			break
		}
		if .IsZero() {
			<-.writeChan
		} else {
			select {
			case <-.writeChan:
			case <-.C:
			}
		}
		.mutex.Lock()
	}

	if  == len() {
		return false, , nil
	}
	if .shutdownErr != nil {
		return false, , .shutdownErr
	}
	if .resetErr != nil {
		.cancellationFlagged = true
		return .isNewlyCompleted(), , .resetErr
	}
	return false, , nil
}

func ( *SendStream) () bool {
	var  protocol.ByteCount
	if .nextFrame != nil {
		 = .nextFrame.DataLen()
	}
	return +protocol.ByteCount(len(.dataForWriting)) <= protocol.MaxPacketBufferSize
}

// popStreamFrame returns the next STREAM frame that is supposed to be sent on this stream
// maxBytes is the maximum length this frame (including frame header) will have.
func ( *SendStream) ( protocol.ByteCount,  protocol.Version) ( ackhandler.StreamFrame,  *wire.StreamDataBlockedFrame,  bool) {
	.mutex.Lock()
	, ,  := .popNewOrRetransmittedStreamFrame(, )
	if  != nil {
		.numOutstandingFrames++
	}
	.mutex.Unlock()

	if  == nil {
		return ackhandler.StreamFrame{}, , 
	}
	return ackhandler.StreamFrame{
		Frame:   ,
		Handler: (*sendStreamAckHandler)(),
	}, , 
}

func ( *SendStream) ( protocol.ByteCount,  protocol.Version) ( *wire.StreamFrame,  *wire.StreamDataBlockedFrame,  bool) {
	if .shutdownErr != nil {
		return nil, nil, false
	}
	if .resetErr != nil {
		 := .reliableOffset()
		if  == 0 || (.writeOffset >=  && len(.retransmissionQueue) == 0) {
			return nil, nil, false
		}
	}

	if len(.retransmissionQueue) > 0 {
		,  := .maybeGetRetransmission(, )
		if  != nil ||  {
			if  == nil {
				return nil, nil, true
			}
			// We always claim that we have more data to send.
			// This might be incorrect, in which case there'll be a spurious call to popStreamFrame in the future.
			return , nil, true
		}
	}

	if len(.dataForWriting) == 0 && .nextFrame == nil {
		if .finishedWriting && !.finSent {
			.finSent = true
			return &wire.StreamFrame{
				StreamID:       .streamID,
				Offset:         .writeOffset,
				DataLenPresent: true,
				Fin:            true,
			}, nil, false
		}
		return nil, nil, false
	}

	 := .flowController.SendWindowSize()
	if  == 0 {
		return nil, nil, true
	}

	// if the stream is canceled, only data up to the reliable size needs to be sent
	 := .reliableOffset()
	if .resetErr != nil &&  > 0 {
		 = min(, -.writeOffset)
	}
	,  := .popNewStreamFrame(, , )
	if  == nil {
		return nil, nil, 
	}
	if .DataLen() > 0 {
		.writeOffset += .DataLen()
		.flowController.AddBytesSent(.DataLen())
	}
	if .resetErr != nil && .writeOffset >=  {
		 = false
	}
	var  *wire.StreamDataBlockedFrame
	// If the entire send window is used, the stream might have become blocked on stream-level flow control.
	// This is not guaranteed though, because the stream might also have been blocked on connection-level flow control.
	if .DataLen() ==  && .flowController.IsNewlyBlocked() {
		 = &wire.StreamDataBlockedFrame{StreamID: .streamID, MaximumStreamData: .writeOffset}
	}
	.Fin = .finishedWriting && .dataForWriting == nil && .nextFrame == nil && !.finSent
	if .Fin {
		.finSent = true
	}
	return , , 
}

// popNewStreamFrame returns a new STREAM frame to send for this stream
// hasMoreData says if there's more data to send, *not* taking into account the reliable size
func ( *SendStream) (,  protocol.ByteCount,  protocol.Version) ( *wire.StreamFrame,  bool) {
	if .nextFrame != nil {
		 := min(, .nextFrame.MaxDataLen(, ))
		if  == 0 {
			return nil, true
		}
		 := .nextFrame
		.nextFrame = nil
		if .DataLen() >  {
			.nextFrame = wire.GetStreamFrame()
			.nextFrame.StreamID = .streamID
			.nextFrame.Offset = .writeOffset + 
			.nextFrame.Data = .nextFrame.Data[:.DataLen()-]
			.nextFrame.DataLenPresent = true
			copy(.nextFrame.Data, .Data[:])
			.Data = .Data[:]
		} else {
			.signalWrite()
		}
		return , .nextFrame != nil || .dataForWriting != nil
	}

	 := wire.GetStreamFrame()
	.Fin = false
	.StreamID = .streamID
	.Offset = .writeOffset
	.DataLenPresent = true
	.Data = .Data[:0]

	 = .popNewStreamFrameWithoutBuffer(, , , )
	if len(.Data) == 0 && !.Fin {
		.PutBack()
		return nil, 
	}
	return , 
}

func ( *SendStream) ( *wire.StreamFrame, ,  protocol.ByteCount,  protocol.Version) bool {
	 := .MaxDataLen(, )
	if  == 0 { // a STREAM frame must have at least one byte of data
		return .dataForWriting != nil || .nextFrame != nil || .finishedWriting
	}
	.getDataForWriting(, min(, ))

	return .dataForWriting != nil || .nextFrame != nil || .finishedWriting
}

func ( *SendStream) ( protocol.ByteCount,  protocol.Version) (*wire.StreamFrame, bool /* has more retransmissions */) {
	 := .retransmissionQueue[0]
	,  := .MaybeSplitOffFrame(, )
	if  {
		return , true
	}
	.retransmissionQueue = .retransmissionQueue[1:]
	return , len(.retransmissionQueue) > 0
}

func ( *SendStream) ( *wire.StreamFrame,  protocol.ByteCount) {
	if protocol.ByteCount(len(.dataForWriting)) <=  {
		.Data = .Data[:len(.dataForWriting)]
		copy(.Data, .dataForWriting)
		.dataForWriting = nil
		.signalWrite()
		return
	}
	.Data = .Data[:]
	copy(.Data, .dataForWriting)
	.dataForWriting = .dataForWriting[:]
	if .canBufferStreamFrame() {
		.signalWrite()
	}
}

func ( *SendStream) () bool {
	if .completed {
		return false
	}
	if .nextFrame != nil && .nextFrame.DataLen() > 0 {
		return false
	}
	// We need to keep the stream around until all frames have been sent and acknowledged.
	if .numOutstandingFrames > 0 || len(.retransmissionQueue) > 0 || .queuedResetStreamFrame != nil {
		return false
	}
	// The stream is completed if we sent the FIN.
	if .finSent {
		.completed = true
		return true
	}
	// The stream is also completed if:
	// 1. the application called CancelWrite, or
	// 2. we received a STOP_SENDING, and
	// 		* the application consumed the error via Write, or
	//		* the application called Close
	if .resetErr != nil && (.cancellationFlagged || .finishedWriting) {
		.completed = true
		return true
	}
	return false
}

// Close closes the write-direction of the stream.
// Future calls to Write are not permitted after calling Close.
// It must not be called concurrently with Write.
// It must not be called after calling CancelWrite.
func ( *SendStream) () error {
	.mutex.Lock()
	if .shutdownErr != nil || .finishedWriting {
		.mutex.Unlock()
		return nil
	}
	.finishedWriting = true
	 := .resetErr != nil
	if  {
		.cancellationFlagged = true
	}
	 := .isNewlyCompleted()
	.mutex.Unlock()

	if  {
		.sender.onStreamCompleted(.streamID)
	}
	if  {
		return fmt.Errorf("close called for canceled stream %d", .streamID)
	}
	.sender.onHasStreamData(.streamID, ) // need to send the FIN, must be called without holding the mutex

	.ctxCancel(nil)
	return nil
}

// SetReliableBoundary marks the data written to this stream so far as reliable.
// It is valid to call this function multiple times, thereby increasing the reliable size.
// It only has an effect if the peer enabled support for the RESET_STREAM_AT extension,
// otherwise, it is a no-op.
func ( *SendStream) () {
	.mutex.Lock()
	defer .mutex.Unlock()

	.reliableSize = .writeOffset
	if .nextFrame != nil {
		.reliableSize += .nextFrame.DataLen()
	}
}

// returnFramesToPool returns all queued frames to the sync.Pool
func ( *SendStream) () {
	for ,  := range .retransmissionQueue {
		.PutBack()
	}
	clear(.retransmissionQueue)
	.retransmissionQueue = nil
	if .nextFrame != nil {
		.nextFrame.PutBack()
		.nextFrame = nil
	}
}

// CancelWrite aborts sending on this stream.
// Data already written, but not yet delivered to the peer is not guaranteed to be delivered reliably.
// Write will unblock immediately, and future calls to Write will fail.
// When called multiple times it is a no-op.
// When called after Close, it aborts reliable delivery of outstanding stream data.
// Note that there is no guarantee if the peer will receive the FIN or the cancellation error first.
func ( *SendStream) ( StreamErrorCode) {
	.mutex.Lock()
	if .shutdownErr != nil {
		.mutex.Unlock()
		return
	}

	.cancellationFlagged = true

	if .resetErr != nil {
		 := .isNewlyCompleted()
		.mutex.Unlock()
		// The user has called CancelWrite. If the previous cancellation was because of a
		// STOP_SENDING, we don't need to flag the error to the user anymore.
		if  {
			.sender.onStreamCompleted(.streamID)
		}
		return
	}
	.resetErr = &StreamError{StreamID: .streamID, ErrorCode: , Remote: false}
	.ctxCancel(.resetErr)

	 := .reliableOffset()
	if  == 0 {
		.numOutstandingFrames = 0
		.returnFramesToPool()
	}
	.queuedResetStreamFrame = &wire.ResetStreamFrame{
		StreamID:  .streamID,
		FinalSize: max(.writeOffset, ),
		ErrorCode: ,
		// if the peer doesn't support the extension, the reliable offset will always be 0
		ReliableSize: ,
	}
	if  > 0 {
		if .nextFrame != nil {
			if .nextFrame.Offset >=  {
				.nextFrame.PutBack()
				.nextFrame = nil
			} else if .nextFrame.Offset+.nextFrame.DataLen() >  {
				.nextFrame.Data = .nextFrame.Data[:-.nextFrame.Offset]
			}
		}
		if len(.retransmissionQueue) > 0 {
			 := make([]*wire.StreamFrame, 0, len(.retransmissionQueue))
			for ,  := range .retransmissionQueue {
				if .Offset >=  {
					.PutBack()
					continue
				}
				if .Offset+.DataLen() <=  {
					 = append(, )
				} else {
					.Data = .Data[:-.Offset]
					 = append(, )
				}
			}
			.retransmissionQueue = 
		}
	}
	.mutex.Unlock()

	.signalWrite()
	.sender.onHasStreamControlFrame(.streamID, )
}

func ( *SendStream) () {
	.mutex.Lock()
	.supportsResetStreamAt = true
	.mutex.Unlock()
}

func ( *SendStream) ( protocol.ByteCount) {
	 := .flowController.UpdateSendWindow()
	if ! { // duplicate or reordered MAX_STREAM_DATA frame
		return
	}
	.mutex.Lock()
	 := .dataForWriting != nil || .nextFrame != nil
	.mutex.Unlock()
	if  {
		.sender.onHasStreamData(.streamID, )
	}
}

func ( *SendStream) ( *wire.StopSendingFrame) {
	.mutex.Lock()
	if .shutdownErr != nil {
		.mutex.Unlock()
		return
	}

	// If the stream was already cancelled (either locally, or due to a previous STOP_SENDING frame),
	// there's nothing else to do.
	if .resetErr != nil && .reliableOffset() == 0 {
		.mutex.Unlock()
		return
	}
	// if the peer stopped reading from the stream, there's no need to transmit any data reliably
	.reliableSize = 0
	.numOutstandingFrames = 0
	.returnFramesToPool()
	if .resetErr == nil {
		.resetErr = &StreamError{StreamID: .streamID, ErrorCode: .ErrorCode, Remote: true}
		.ctxCancel(.resetErr)
	}
	.queuedResetStreamFrame = &wire.ResetStreamFrame{
		StreamID:  .streamID,
		FinalSize: .writeOffset,
		ErrorCode: .resetErr.ErrorCode,
	}
	.mutex.Unlock()

	.signalWrite()
	.sender.onHasStreamControlFrame(.streamID, )
}

func ( *SendStream) (monotime.Time) ( ackhandler.Frame, ,  bool) {
	.mutex.Lock()
	defer .mutex.Unlock()

	if .queuedResetStreamFrame == nil {
		return ackhandler.Frame{}, false, false
	}
	.numOutstandingFrames++
	 := ackhandler.Frame{
		Frame:   .queuedResetStreamFrame,
		Handler: (*sendStreamResetStreamHandler)(),
	}
	.queuedResetStreamFrame = nil
	return , true, false
}

func ( *SendStream) () protocol.ByteCount {
	if !.supportsResetStreamAt {
		return 0
	}
	return .reliableSize
}

// The Context is canceled as soon as the write-side of the stream is closed.
// This happens when Close() or CancelWrite() is called, or when the peer
// cancels the read-side of their stream.
// The cancellation cause is set to the error that caused the stream to
// close, or `context.Canceled` in case the stream is closed without error.
func ( *SendStream) () context.Context {
	return .ctx
}

// SetWriteDeadline sets the deadline for future Write calls
// and any currently-blocked Write call.
// Even if write times out, it may return n > 0, indicating that
// some data was successfully written.
// A zero value for t means Write will not time out.
func ( *SendStream) ( time.Time) error {
	.mutex.Lock()
	.deadline = monotime.FromTime()
	.mutex.Unlock()
	.signalWrite()
	return nil
}

// CloseForShutdown closes a stream abruptly.
// It makes Write unblock (and return the error) immediately.
// The peer will NOT be informed about this: the stream is closed without sending a FIN or RST.
func ( *SendStream) ( error) {
	.mutex.Lock()
	if .shutdownErr == nil && !.finishedWriting {
		.shutdownErr = 
		.returnFramesToPool()
	}
	.mutex.Unlock()
	.signalWrite()
}

// signalWrite performs a non-blocking send on the writeChan
func ( *SendStream) () {
	select {
	case .writeChan <- struct{}{}:
	default:
	}
}

type sendStreamAckHandler SendStream

var _ ackhandler.FrameHandler = &sendStreamAckHandler{}

func ( *sendStreamAckHandler) ( wire.Frame) {
	 := .(*wire.StreamFrame)
	.PutBack()

	.mutex.Lock()
	if .resetErr != nil && (*SendStream)().reliableOffset() == 0 {
		.mutex.Unlock()
		return
	}
	.numOutstandingFrames--
	if .numOutstandingFrames < 0 {
		panic("numOutStandingFrames negative")
	}
	 := (*SendStream)().isNewlyCompleted()
	.mutex.Unlock()

	if  {
		.sender.onStreamCompleted(.streamID)
	}
}

func ( *sendStreamAckHandler) ( wire.Frame) {
	 := .(*wire.StreamFrame)
	.mutex.Lock()
	// If the reliable size was 0 when the stream was cancelled,
	// the number of outstanding frames was immediately set to 0, and the retransmission queue was dropped.
	if .resetErr != nil && (*SendStream)().reliableOffset() == 0 {
		// Return the frame to pool since it won't be retransmitted
		.PutBack()
		.mutex.Unlock()
		return
	}
	.numOutstandingFrames--
	if .numOutstandingFrames < 0 {
		panic("numOutStandingFrames negative")
	}

	if .resetErr != nil && (*SendStream)().reliableOffset() > 0 {
		// If the stream was reset, and this frame is beyond the reliable offset,
		// it doesn't need to be retransmitted.
		if .Offset >= (*SendStream)().reliableOffset() {
			.PutBack()
			// If this frame was the last one tracked, losing it might cause the stream to be completed.
			 := (*SendStream)().isNewlyCompleted()
			.mutex.Unlock()
			if  {
				.sender.onStreamCompleted(.streamID)
			}
			return
		}
		// If the payload of the frame extends beyond the reliable size,
		// truncate the frame to the reliable size.
		if .Offset+.DataLen() > (*SendStream)().reliableOffset() {
			.Data = .Data[:(*SendStream)().reliableOffset()-.Offset]
		}
	}

	.DataLenPresent = true
	.retransmissionQueue = append(.retransmissionQueue, )
	.mutex.Unlock()

	.sender.onHasStreamData(.streamID, (*SendStream)())
}

type sendStreamResetStreamHandler SendStream

var _ ackhandler.FrameHandler = &sendStreamResetStreamHandler{}

func ( *sendStreamResetStreamHandler) ( wire.Frame) {
	 := .(*wire.ResetStreamFrame)
	.mutex.Lock()
	// If the peer sent a STOP_SENDING after we sent a RESET_STREAM_AT frame,
	// we sent 1. reduced the reliable size to 0 and 2. sent a RESET_STREAM frame.
	// In this case, we don't care about the acknowledgment of this frame.
	if .ReliableSize != (*SendStream)().reliableOffset() {
		.mutex.Unlock()
		return
	}
	.numOutstandingFrames--
	if .numOutstandingFrames < 0 {
		panic("numOutStandingFrames negative")
	}
	 := (*SendStream)().isNewlyCompleted()
	.mutex.Unlock()

	if  {
		.sender.onStreamCompleted(.streamID)
	}
}

func ( *sendStreamResetStreamHandler) ( wire.Frame) {
	 := .(*wire.ResetStreamFrame)
	.mutex.Lock()
	// If the peer sent a STOP_SENDING after we sent a RESET_STREAM_AT frame,
	// we sent 1. reduced the reliable size to 0 and 2. sent a RESET_STREAM frame.
	// In this case, the loss of the RESET_STREAM_AT frame can be ignored.
	if .ReliableSize != (*SendStream)().reliableOffset() {
		.mutex.Unlock()
		return
	}
	.queuedResetStreamFrame = 
	.numOutstandingFrames--
	.mutex.Unlock()
	.sender.onHasStreamControlFrame(.streamID, (*SendStream)())
}