// sendAck makes a best effort to ack or nack the evaluation.
// Any errors are logged but swallowed.
420293
func (w *Worker) sendAck(evalID, token string, ack bool) {
	defer metrics.MeasureSince([]string{"nomad", "worker", "send_ack"}, time.Now())
	// Setup the request
	req := structs.EvalAckRequest{
		EvalID: evalID,
		Token:  token,
		WriteRequest: structs.WriteRequest{
			Region: w.srv.config.Region,
		},
	}
	var resp structs.GenericResponse

	// Determine if this is an Ack or Nack
	verb := "ack"
	endpoint := "Eval.Ack"
	if !ack {
		verb = "nack"
		endpoint = "Eval.Nack"
	}

	// Make the RPC call
	err := w.srv.RPC(endpoint, &req, &resp)
	if err != nil {
		w.logger.Error(fmt.Sprintf("failed to %s evaluation", verb), "eval_id", evalID, "error", err)
	} else {
		w.logger.Debug(fmt.Sprintf("%s evaluation", verb), "eval_id", evalID)
	}
}
392660
func (s SMTPClientMock) SendMail(from string, to []string, msg []byte) error {
	if s.valid == true {
		return nil
	}
	return errors.New("smtp send error")
}
372442
func (s *sender) sendAck() {
	s.sendSegment(buffer.VectorisedView{}, header.TCPFlagAck, s.sndNxt)
}
317343
func sendPacket(w io.Writer, m encoding.BinaryMarshaler) error {
	bb, err := m.MarshalBinary()
	if err != nil {
		return errors.Errorf("binary marshaller failed: %v", err)
	}
	if debugDumpTxPacketBytes {
		debug("send packet: %s %d bytes %x", fxp(bb[0]), len(bb), bb[1:])
	} else if debugDumpTxPacket {
		debug("send packet: %s %d bytes", fxp(bb[0]), len(bb))
	}
	// Slide packet down 4 bytes to make room for length header.
	packet := append(bb, make([]byte, 4)...) // optimistically assume bb has capacity
	copy(packet[4:], bb)
	binary.BigEndian.PutUint32(packet[:4], uint32(len(bb)))

	_, err = w.Write(packet)
	if err != nil {
		return errors.Errorf("failed to send packet: %v", err)
	}
	return nil
}
575300
func (c *Chan) SendChan() chan<- interface{} {

	c.mutx.Lock()
	defer c.mutx.Unlock()

	if c.sendch == nil {
		c.sendch = make(chan interface{})
		go c.sendLoop()
	}
	return c.sendch
}
1338413
func (e *Error) DecodeMsgpack(dec *msgpack.Decoder) error {
	var msg messageType
	err := dec.Decode(&msg)
	if err != nil {
		return err
	}
	switch msg {
	case ErrorLocal:
		var er *Error
		err := dec.Decode(&er)
		if err != nil {
			return err
		}
		e.err = er
	case ErrorGo:
		var er GoError
		err := dec.Decode(&er)
		if err != nil {
			return err
		}
		e.err = er
	default:
		return errors.New("protocol error")
	}
	err = dec.Decode(&e.args)
	if err != nil {
		return err
	}
	err = dec.Decode(&e.pkg)
	if err != nil {
		return err
	}
	err = dec.Decode(&e.file)
	if err != nil {
		return err
	}
	err = dec.Decode(&e.line)
	if err != nil {
		return err
	}
	err = dec.Decode(&e.debugInfo)
	if err != nil {
		return err
	}
	err = dec.Decode(&msg)
	if err != nil {
		return err
	}
	switch msg {
	case NextIsNill:
		return nil
	case Next:
		err = dec.Decode(&e.next)
		if err != nil {
			return err
		}
	default:
		return errors.New("protocol error")
	}
	return nil
}
534754
func (c *cubicState) HandleNDupAcks() {
	// See: https://tools.ietf.org/html/rfc8312#section-4.5
	c.numCongestionEvents++
	c.t = time.Now()
	c.wLastMax = c.wMax
	c.wMax = float64(c.s.sndCwnd)

	c.fastConvergence()
	c.reduceSlowStartThreshold()
}
147799
func (mp *MachineProvider) ack(ctx context.Context, hostname, backend string) error {
	return mp.client.Ack(&machine.ComponentsMachineProviderRpcMessagesAckRequest{
		Backend:  backend,
		Hostname: hostname,
	}).Context(ctx).Do()
}
461942
func (s *StanServer) processAck(c *channel, sub *subState, sequence uint64, fromUser bool) {
	var stalled bool

	// This is immutable, so can grab outside of sub's lock.
	// If we have a queue group, we want to grab queue's lock before
	// sub's lock.
	qs := sub.qstate
	if qs != nil {
		qs.Lock()
	}

	sub.Lock()

	persistAck := func(aSub *subState) bool {
		if err := aSub.store.AckSeqPending(aSub.ID, sequence); err != nil {
			s.log.Errorf("[Client:%s] Unable to persist ack for subid=%d, subject=%s, seq=%d, err=%v",
				aSub.ClientID, aSub.ID, aSub.subject, sequence, err)
			return false
		}
		return true
	}

	if _, found := sub.acksPending[sequence]; found {
		// If in cluster mode, schedule replication of the ack.
		if s.isClustered {
			s.collectSentOrAck(sub, replicateAck, sequence)
		}
		if s.trace && fromUser {
			s.log.Tracef("[Client:%s] Processing ack for subid=%d, subject=%s, seq=%d",
				sub.ClientID, sub.ID, sub.subject, sequence)
		}
		if !persistAck(sub) {
			sub.Unlock()
			if qs != nil {
				qs.Unlock()
			}
			return
		}
		delete(sub.acksPending, sequence)
	} else if qs != nil && fromUser {
		// For queue members, if this is not an internally generated ACK
		// and we don't find the sequence in this sub's pending, we are
		// going to look for it in other members and process it if found.
		sub.Unlock()
		for _, qsub := range qs.subs {
			if qsub == sub {
				continue
			}
			qsub.Lock()
			if _, found := qsub.acksPending[sequence]; found {
				delete(qsub.acksPending, sequence)
				persistAck(qsub)
				qsub.Unlock()
				break
			}
			qsub.Unlock()
		}
		sub.Lock()
		// Proceed with original sub (regardless if member was found
		// or not) so that server sends more messages if needed.
	}
	if sub.stalled && int32(len(sub.acksPending)) < sub.MaxInFlight {
		// For queue, we must not check the queue stalled count here. The queue
		// as a whole may not be stalled, yet, if this sub was stalled, it is
		// not now since the pending acks is below MaxInflight. The server should
		// try to send available messages.
		// It works also if the queue *was* stalled (all members were stalled),
		// then this member is no longer stalled, which release the queue.

		// Trigger send of available messages by setting this to true.
		stalled = true

		// Clear the stalled flag from this sub
		sub.stalled = false
		// .. and update the queue's stalled members count if this is a queue sub.
		if qs != nil && qs.stalledSubCount > 0 {
			qs.stalledSubCount--
		}
	}
	sub.Unlock()
	if qs != nil {
		qs.Unlock()
	}

	// Leave the reset/cancel of the ackTimer to the redelivery cb.

	if !stalled {
		return
	}

	if sub.qstate != nil {
		s.sendAvailableMessagesToQueue(c, sub.qstate)
	} else {
		s.sendAvailableMessages(c, sub)
	}
}
334418
func (m *Driver) SendPacket(packet *common.MAVLinkPacket) (err error) {
	_, err = m.adaptor().Write(packet.Pack())
	return err
}
1048282
func (rtm *RTM) handleAck(event json.RawMessage) {
	ack := &AckMessage{}
	if err := json.Unmarshal(event, ack); err != nil {
		rtm.Debugln("RTM Error unmarshalling 'ack' event:", err)
		rtm.Debugln(" -> Erroneous 'ack' event:", string(event))
		return
	}

	if ack.Ok {
		rtm.IncomingEvents <- RTMEvent{"ack", ack}
	} else if ack.RTMResponse.Error != nil {
		// As there is no documentation for RTM error-codes, this
		// identification of a rate-limit warning is very brittle.
		if ack.RTMResponse.Error.Code == -1 && ack.RTMResponse.Error.Msg == "slow down, too many messages..." {
			rtm.IncomingEvents <- RTMEvent{"ack_error", &RateLimitEvent{}}
		} else {
			rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{ack.Error}}
		}
	} else {
		rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{fmt.Errorf("ack decode failure")}}
	}
}
912286
func (h *receivedPacketTracker) maybeQueueAck(packetNumber protocol.PacketNumber, rcvTime time.Time, shouldInstigateAck, wasMissing bool) {
	h.packetsReceivedSinceLastAck++

	// always ack the first packet
	if h.lastAck == nil {
		h.logger.Debugf("\tQueueing ACK because the first packet should be acknowledged.")
		h.ackQueued = true
		return
	}

	// Send an ACK if this packet was reported missing in an ACK sent before.
	// Ack decimation with reordering relies on the timer to send an ACK, but if
	// missing packets we reported in the previous ack, send an ACK immediately.
	if wasMissing {
		if h.logger.Debug() {
			h.logger.Debugf("\tQueueing ACK because packet %#x was missing before.", packetNumber)
		}
		h.ackQueued = true
	}

	if !h.ackQueued && shouldInstigateAck {
		h.ackElicitingPacketsReceivedSinceLastAck++

		if packetNumber > minReceivedBeforeAckDecimation {
			// ack up to 10 packets at once
			if h.ackElicitingPacketsReceivedSinceLastAck >= ackElicitingPacketsBeforeAck {
				h.ackQueued = true
				if h.logger.Debug() {
					h.logger.Debugf("\tQueueing ACK because packet %d packets were received after the last ACK (using threshold: %d).", h.ackElicitingPacketsReceivedSinceLastAck, ackElicitingPacketsBeforeAck)
				}
			} else if h.ackAlarm.IsZero() {
				// wait for the minimum of the ack decimation delay or the delayed ack time before sending an ack
				ackDelay := utils.MinDuration(ackSendDelay, time.Duration(float64(h.rttStats.MinRTT())*float64(ackDecimationDelay)))
				h.ackAlarm = rcvTime.Add(ackDelay)
				if h.logger.Debug() {
					h.logger.Debugf("\tSetting ACK timer to min(1/4 min-RTT, max ack delay): %s (%s from now)", ackDelay, time.Until(h.ackAlarm))
				}
			}
		} else {
			// send an ACK every 2 ack-eliciting packets
			if h.ackElicitingPacketsReceivedSinceLastAck >= initialAckElicitingPacketsBeforeAck {
				if h.logger.Debug() {
					h.logger.Debugf("\tQueueing ACK because packet %d packets were received after the last ACK (using initial threshold: %d).", h.ackElicitingPacketsReceivedSinceLastAck, initialAckElicitingPacketsBeforeAck)
				}
				h.ackQueued = true
			} else if h.ackAlarm.IsZero() {
				if h.logger.Debug() {
					h.logger.Debugf("\tSetting ACK timer to max ack delay: %s", ackSendDelay)
				}
				h.ackAlarm = rcvTime.Add(ackSendDelay)
			}
		}
		// If there are new missing packets to report, set a short timer to send an ACK.
		if h.hasNewMissingPackets() {
			// wait the minimum of 1/8 min RTT and the existing ack time
			ackDelay := time.Duration(float64(h.rttStats.MinRTT()) * float64(shortAckDecimationDelay))
			ackTime := rcvTime.Add(ackDelay)
			if h.ackAlarm.IsZero() || h.ackAlarm.After(ackTime) {
				h.ackAlarm = ackTime
				if h.logger.Debug() {
					h.logger.Debugf("\tSetting ACK timer to 1/8 min-RTT: %s (%s from now)", ackDelay, time.Until(h.ackAlarm))
				}
			}
		}
	}

	if h.ackQueued {
		// cancel the ack alarm
		h.ackAlarm = time.Time{}
	}
}
610500
func (pack *Package) MultiAck() (err error) {
	if pack.Collection == nil {
		return fmt.Errorf("cannot MultiAck single package")
	}
	// TODO write in lua
	for i := 0; i <= pack.index(); i++ {
		var p *Package
		p = (*pack.Collection)[i]
		// if the package has already been acked just skip
		if p.Acked == true {
			continue
		}

		err = pack.Consumer.ackPackage(p)
		if err != nil {
			break
		}
		p.Acked = true
	}
	return
}
341783
func (stc *ScatterConn) MessageAck(ctx context.Context, rss []*srvtopo.ResolvedShard, values [][]*querypb.Value, name string) (int64, error) {
	var mu sync.Mutex
	var totalCount int64
	allErrors := stc.multiGo(ctx, "MessageAck", rss, topodatapb.TabletType_MASTER, func(rs *srvtopo.ResolvedShard, i int) error {
		count, err := rs.QueryService.MessageAck(ctx, rs.Target, name, values[i])
		if err != nil {
			return err
		}
		mu.Lock()
		totalCount += count
		mu.Unlock()
		return nil
	})
	return totalCount, allErrors.AggrError(vterrors.Aggregate)
}
770094
func (m *MockSentPacketHandler) SentPacket(arg0 *ackhandler.Packet) {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "SentPacket", arg0)
}
1030012
func sendAttention(buf *tdsBuffer) error {
	buf.BeginPacket(packAttention, false)
	return buf.FinishPacket()
}
1004785
func (b *EvalBroker) Nack(evalID, token string) error {
	b.l.Lock()
	defer b.l.Unlock()

	// Always delete the requeued evaluation since the Nack means the requeue is
	// invalid.
	delete(b.requeue, token)

	// Lookup the unack'd eval
	unack, ok := b.unack[evalID]
	if !ok {
		return fmt.Errorf("Evaluation ID not found")
	}
	if unack.Token != token {
		return fmt.Errorf("Token does not match for Evaluation ID")
	}

	// Stop the timer, doesn't matter if we've missed it
	unack.NackTimer.Stop()

	// Cleanup
	delete(b.unack, evalID)

	// Update the stats
	b.stats.TotalUnacked -= 1
	bySched := b.stats.ByScheduler[unack.Eval.Type]
	bySched.Unacked -= 1

	// Check if we've hit the delivery limit, and re-enqueue
	// in the failedQueue
	if dequeues := b.evals[evalID]; dequeues >= b.deliveryLimit {
		b.enqueueLocked(unack.Eval, failedQueue)
	} else {
		e := unack.Eval
		e.Wait = b.nackReenqueueDelay(e, dequeues)

		// See if there should be a delay before re-enqueuing
		if e.Wait > 0 {
			b.processWaitingEnqueue(e)
		} else {
			b.enqueueLocked(e, e.Type)
		}
	}

	return nil
}