// RollForward implements tumble.Mutation
177791
func (t *TimeoutExecution) RollForward(c context.Context) (muts []tumble.Mutation, err error) {
	e := model.ExecutionFromID(c, t.For)

	if err = ds.Get(c, e); err != nil {
		return
	}
	if e.State != t.State {
		logging.Errorf(c, "EARLY EXIT: %s v %s", e.State, t.State)
		return
	}

	// will be overwritten if this execution is STOPPING and the timeout is not
	// abnormal
	rslt := &dm.Result{AbnormalFinish: &dm.AbnormalFinish{
		Reason: fmt.Sprintf("DM timeout (%s)", e.State),
		Status: dm.AbnormalFinish_TIMED_OUT}}

	if e.State == dm.Execution_STOPPING {
		// if it's supposed to be STOPPING, maybe we just missed a notification from
		// the distributor (or the distributor is not using pubsub).
		reg := distributor.GetRegistry(c)
		var dist distributor.D
		var vers string
		dist, vers, err = reg.MakeDistributor(c, e.DistributorConfigName)

		if vers != "" && vers != e.DistributorConfigVersion {
			logging.Fields{
				"cfg_name":      e.DistributorConfigName,
				"orig_cfg_vers": e.DistributorConfigVersion,
				"cur_cfg_vers":  vers,
			}.Warningf(c, "mismatched distributor config versions")
		}

		// TODO(iannucci): make this set the REJECTED state if we loaded the config,
		// but the distributor no longer exists.
		if err != nil {
			logging.Fields{
				logging.ErrorKey: err,
				"cfgName":        e.DistributorConfigName,
			}.Errorf(c, "Could not MakeDistributor")
			return
		}
		var realRslt *dm.Result
		q := model.QuestFromID(t.For.Quest)
		if err = ds.Get(ds.WithoutTransaction(c), q); err != nil {
			err = errors.Annotate(err, "loading quest").Err()
			return
		}
		realRslt, err = dist.GetStatus(&q.Desc, distributor.Token(e.DistributorToken))
		if (err != nil || realRslt == nil) && t.TimeoutAttempt < maxTimeoutAttempts {
			logging.Fields{
				logging.ErrorKey:  err,
				"task_result":     realRslt,
				"timeout_attempt": t.TimeoutAttempt,
			}.Infof(c, "GetStatus failed/nop'd while timing out STOPPING execution")
			// TODO(riannucci): do randomized exponential backoff instead of constant
			// backoff? Kinda don't really want to spend more than 1.5m waiting
			// anyway, and the actual GetStatus call does local retries already, so
			// hopefully this is fine. If this is wrong, the distributor should adjust
			// its timeToStop value to be better.
			t.Deadline = t.Deadline.Add(time.Second * 30)
			t.TimeoutAttempt++
			err = nil
			muts = append(muts, t)
			return
		}

		if err != nil {
			rslt.AbnormalFinish.Reason = fmt.Sprintf("DM timeout (%s) w/ error: %s", e.State, err)
			err = nil
		} else if realRslt != nil {
			rslt = realRslt
		}
	}

	muts = append(muts, &FinishExecution{t.For, rslt})
	return
}
310596
func ForwardsSkip(to int, fx func(int, func())) {
	for i := 1; i <= to; i++ {
		fx(i, func() { i++ })
	}
}
768929
func WithForwardTimeout(d time.Duration) Option {
	return func(opts *options) {
		opts.forwardTimeout = d
	}
}
1311852
func (mp *Proxy) Rollback(ctx context.Context, session *ProxySession) error {
	return mp.doRollback(ctx, session)
}
831436
func (r *RecordCompletion) RollForward(c context.Context) (muts []tumble.Mutation, err error) {
	bdg := &model.BackDepGroup{Dependee: *r.For}
	if err = ds.Get(c, bdg); err != nil && err != ds.ErrNoSuchEntity {
		return
	}

	needProp := make([]*model.BackDep, 0, completionLimit)

	q := (ds.NewQuery("BackDep").
		Ancestor(ds.KeyForObj(c, bdg)).
		Eq("Propagated", false).
		Limit(completionLimit))

	if err = ds.GetAll(c, q, &needProp); err != nil {
		return
	}

	if len(needProp) > 0 {
		muts = make([]tumble.Mutation, len(needProp))

		for i, bdep := range needProp {
			bdep.Propagated = true
			muts[i] = &AckFwdDep{bdep.Edge()}
		}

		if len(needProp) == completionLimit {
			// Append ourself if there might be more to do!
			muts = append(muts, r)
		}

		if err = ds.Put(c, needProp); err != nil {
			return
		}
	}

	if !bdg.AttemptFinished {
		bdg.AttemptFinished = true
		if err = ds.Put(c, bdg); err != nil {
			return
		}
	}

	return
}
567825
func (s *DomainsService) CreateEmailForward(accountID string, domainIdentifier string, forwardAttributes EmailForward) (*emailForwardResponse, error) {
	path := versioned(emailForwardPath(accountID, domainIdentifier, 0))
	forwardResponse := &emailForwardResponse{}

	resp, err := s.client.post(path, forwardAttributes, forwardResponse)
	if err != nil {
		return nil, err
	}

	forwardResponse.HttpResponse = resp
	return forwardResponse, nil
}
1025875
func (c *client) Rollback(namespace, name string, build int, target string, params map[string]string) (*Build, error) {
	out := new(Build)
	val := mapValues(params)
	val.Set("target", target)
	uri := fmt.Sprintf(pathRollback, c.addr, namespace, name, build, val.Encode())
	err := c.post(uri, nil, out)
	return out, err
}
505222
func Forwards(to int, fx func(int)) {
	for i := 1; i <= to; i++ {
		fx(i)
	}
}
1209613
func (f *FinishAttempt) RollForward(c context.Context) (muts []tumble.Mutation, err error) {
	atmpt, ex, err := model.InvalidateExecution(c, f.Auth)
	if err != nil {
		logging.WithError(err).Errorf(c, "could not invalidate execution")
		return
	}

	if err = ResetExecutionTimeout(c, ex); err != nil {
		logging.WithError(err).Errorf(c, "could not reset timeout")
		return
	}

	ar := &model.AttemptResult{
		Attempt: model.AttemptKeyFromID(c, &atmpt.ID),
		Data:    *f.Data,
	}

	rslt := *f.Data
	atmpt.Result.Data = &rslt
	atmpt.Result.Data.Object = ""

	err = errors.Annotate(ds.Put(c, atmpt, ar), "during Put").Tag(grpcutil.Tag.With(codes.Internal)).Err()
	return
}
379437
func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {
	lState := makeFBOLockState()
	fbo.headLock.RLock(lState)
	defer fbo.headLock.RUnlock(lState)
	if fbo.head != (ImmutableRootMetadata{}) {
		// We're already up to date.
		return
	}
	if !fbo.hasBeenCleared {
		// No reason to fast-forward here if it hasn't ever been
		// cleared.
		return
	}
	fbo.hasBeenCleared = false

	fbo.forcedFastForwards.Add(1)
	fbo.goTracked(func() {
		defer fbo.forcedFastForwards.Done()
		ctx, cancelFunc := fbo.newCtxWithFBOID()
		defer cancelFunc()

		fbo.log.CDebugf(ctx, "Forcing a fast-forward")
		var currHead ImmutableRootMetadata
		var err error
	getMD:
		for i := 0; ; i++ {
			currHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)
			switch errors.Cause(err).(type) {
			case nil:
				break getMD
			case kbfsmd.ServerErrorUnauthorized:
				// The MD server connection might not be authorized
				// yet, so give it a few chances to go through.
				if i > 5 {
					fbo.log.CDebugf(ctx,
						"Still unauthorized for TLF %s; giving up fast-forward",
						fbo.id())
					return
				}
				if i == 0 {
					fbo.log.CDebugf(
						ctx, "Got unauthorized error when fast-forwarding %s; "+
							"trying again after a delay", fbo.id())
				}
				time.Sleep(1 * time.Second)
			default:
				fbo.log.CDebugf(ctx, "Fast-forward failed: %+v", err)
				return
			}
		}
		if currHead == (ImmutableRootMetadata{}) {
			fbo.log.CDebugf(ctx, "No MD yet")
			return
		}
		fbo.log.CDebugf(ctx, "Current head is revision %d", currHead.Revision())

		lState := makeFBOLockState()
		// Kick off partial prefetching once the latest merged
		// revision is set.
		defer func() {
			if err == nil {
				fbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)
			}
		}()

		fbo.mdWriterLock.Lock(lState)
		defer fbo.mdWriterLock.Unlock(lState)
		fbo.headLock.Lock(lState)
		defer fbo.headLock.Unlock(lState)
		if fbo.head != (ImmutableRootMetadata{}) {
			// We're already up to date.
			fbo.log.CDebugf(ctx, "Already up-to-date: %v", err)
			return
		}

		err = fbo.doFastForwardLocked(ctx, lState, currHead)
		if err != nil {
			fbo.log.CDebugf(ctx, "Fast-forward failed: %v", err)
		}
	})
}
345396
func (b *SimulatedBackend) Rollback() {
	b.mu.Lock()
	defer b.mu.Unlock()

	b.rollback()
}
655034
func (f *RemoteRuntime) PortForward(ctx context.Context, req *kubeapi.PortForwardRequest) (*kubeapi.PortForwardResponse, error) {
	return f.RuntimeService.PortForward(req)
}
1004303
func (f *NotifyExecution) RollForward(c context.Context) (muts []tumble.Mutation, err error) {
	reg := GetRegistry(c)
	dist, _, err := reg.MakeDistributor(c, f.CfgName)
	if err != nil {
		logging.Fields{
			logging.ErrorKey: err,
			"cfg":            f.CfgName,
		}.Errorf(c, "Failed to make distributor")
		return
	}

	q := &model.Quest{ID: f.Notification.ID.Quest}
	if err := ds.Get(ds.WithoutTransaction(c), q); err != nil {
		return nil, errors.Annotate(err, "getting Quest").Err()
	}
	rslt, err := dist.HandleNotification(&q.Desc, f.Notification)
	if err != nil {
		// TODO(riannucci): check for transient/non-transient
		logging.Fields{
			logging.ErrorKey: err,
			"cfg":            f.CfgName,
		}.Errorf(c, "Failed to handle notification")
		return
	}
	if rslt != nil {
		return reg.FinishExecution(c, f.Notification.ID, rslt)
	}
	return
}
987120
func (b *Btelegram) handleForwarded(rmsg *config.Message, message *tgbotapi.Message) {
	if message.ForwardFrom != nil {
		usernameForward := ""
		if b.GetBool("UseFirstName") {
			usernameForward = message.ForwardFrom.FirstName
		}
		if usernameForward == "" {
			usernameForward = message.ForwardFrom.UserName
			if usernameForward == "" {
				usernameForward = message.ForwardFrom.FirstName
			}
		}
		if usernameForward == "" {
			usernameForward = unknownUser
		}
		rmsg.Text = "Forwarded from " + usernameForward + ": " + rmsg.Text
	}
}
1109680
func NewLogForwarder(args OpenLogForwarderArgs) (*LogForwarder, error) {
	lf := &LogForwarder{
		args:      args,
		enabledCh: make(chan bool, 1),
	}
	err := catacomb.Invoke(catacomb.Plan{
		Site: &lf.catacomb,
		Work: func() error {
			return errors.Trace(lf.loop())
		},
	})
	if err != nil {
		return nil, errors.Trace(err)
	}
	return lf, nil
}
450066
func (s *session) rollbackOnError(ctx context.Context) {
	if !s.sessionVars.InTxn() {
		s.RollbackTxn(ctx)
	}
}
1186335
func (s *Switch) handlePacketForward(packet *htlcPacket) error {
	switch htlc := packet.htlc.(type) {

	// Channel link forwarded us a new htlc, therefore we initiate the
	// payment circuit within our internal state so we can properly forward
	// the ultimate settle message back latter.
	case *lnwire.UpdateAddHTLC:
		if packet.incomingChanID == sourceHop {
			// A blank incomingChanID indicates that this is
			// a pending user-initiated payment.
			return s.handleLocalDispatch(packet)
		}

		s.indexMtx.RLock()
		targetLink, err := s.getLinkByShortID(packet.outgoingChanID)
		if err != nil {
			s.indexMtx.RUnlock()

			// If packet was forwarded from another channel link
			// than we should notify this link that some error
			// occurred.
			failure := &lnwire.FailUnknownNextPeer{}
			addErr := fmt.Errorf("unable to find link with "+
				"destination %v", packet.outgoingChanID)

			return s.failAddPacket(packet, failure, addErr)
		}
		targetPeerKey := targetLink.Peer().PubKey()
		interfaceLinks, _ := s.getLinks(targetPeerKey)
		s.indexMtx.RUnlock()

		// We'll keep track of any HTLC failures during the link
		// selection process. This way we can return the error for
		// precise link that the sender selected, while optimistically
		// trying all links to utilize our available bandwidth.
		linkErrs := make(map[lnwire.ShortChannelID]lnwire.FailureMessage)

		// Try to find destination channel link with appropriate
		// bandwidth.
		var destination ChannelLink
		for _, link := range interfaceLinks {
			// We'll skip any links that aren't yet eligible for
			// forwarding.
			switch {
			case !link.EligibleToForward():
				continue

			// If the link doesn't yet have a source chan ID, then
			// we'll skip it as well.
			case link.ShortChanID() == sourceHop:
				continue
			}

			// Before we check the link's bandwidth, we'll ensure
			// that the HTLC satisfies the current forwarding
			// policy of this target link.
			currentHeight := atomic.LoadUint32(&s.bestHeight)
			err := link.HtlcSatifiesPolicy(
				htlc.PaymentHash, packet.incomingAmount,
				packet.amount, packet.incomingTimeout,
				packet.outgoingTimeout, currentHeight,
			)
			if err != nil {
				linkErrs[link.ShortChanID()] = err
				continue
			}

			if link.Bandwidth() >= htlc.Amount {
				destination = link

				break
			}
		}

		switch {
		// If the channel link we're attempting to forward the update
		// over has insufficient capacity, and didn't violate any
		// forwarding policies, then we'll cancel the htlc as the
		// payment cannot succeed.
		case destination == nil && len(linkErrs) == 0:
			// If packet was forwarded from another channel link
			// than we should notify this link that some error
			// occurred.
			var failure lnwire.FailureMessage
			update, err := s.cfg.FetchLastChannelUpdate(
				packet.outgoingChanID,
			)
			if err != nil {
				failure = &lnwire.FailTemporaryNodeFailure{}
			} else {
				failure = lnwire.NewTemporaryChannelFailure(update)
			}

			addErr := fmt.Errorf("unable to find appropriate "+
				"channel link insufficient capacity, need "+
				"%v towards node=%x", htlc.Amount, targetPeerKey)

			return s.failAddPacket(packet, failure, addErr)

		// If we had a forwarding failure due to the HTLC not
		// satisfying the current policy, then we'll send back an
		// error, but ensure we send back the error sourced at the
		// *target* link.
		case destination == nil && len(linkErrs) != 0:
			// At this point, some or all of the links rejected the
			// HTLC so we couldn't forward it. So we'll try to look
			// up the error that came from the source.
			linkErr, ok := linkErrs[packet.outgoingChanID]
			if !ok {
				// If we can't find the error of the source,
				// then we'll return an unknown next peer,
				// though this should never happen.
				linkErr = &lnwire.FailUnknownNextPeer{}
				log.Warnf("unable to find err source for "+
					"outgoing_link=%v, errors=%v",
					packet.outgoingChanID, newLogClosure(func() string {
						return spew.Sdump(linkErrs)
					}))
			}

			addErr := fmt.Errorf("incoming HTLC(%x) violated "+
				"target outgoing link (id=%v) policy: %v",
				htlc.PaymentHash[:], packet.outgoingChanID,
				linkErr)

			return s.failAddPacket(packet, linkErr, addErr)
		}

		// Send the packet to the destination channel link which
		// manages the channel.
		packet.outgoingChanID = destination.ShortChanID()
		return destination.HandleSwitchPacket(packet)

	case *lnwire.UpdateFailHTLC, *lnwire.UpdateFulfillHTLC:
		// If the source of this packet has not been set, use the
		// circuit map to lookup the origin.
		circuit, err := s.closeCircuit(packet)
		if err != nil {
			return err
		}

		fail, isFail := htlc.(*lnwire.UpdateFailHTLC)
		if isFail && !packet.hasSource {
			switch {
			case circuit.ErrorEncrypter == nil:
				// No message to encrypt, locally sourced
				// payment.

			case packet.isResolution:
				// If this is a resolution message, then we'll need to encrypt
				// it as it's actually internally sourced.
				var err error
				// TODO(roasbeef): don't need to pass actually?
				failure := &lnwire.FailPermanentChannelFailure{}
				fail.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
					failure,
				)
				if err != nil {
					err = fmt.Errorf("unable to obfuscate "+
						"error: %v", err)
					log.Error(err)
				}

			default:
				// Otherwise, it's a forwarded error, so we'll perform a
				// wrapper encryption as normal.
				fail.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
					fail.Reason,
				)
			}
		} else if !isFail && circuit.Outgoing != nil {
			// If this is an HTLC settle, and it wasn't from a
			// locally initiated HTLC, then we'll log a forwarding
			// event so we can flush it to disk later.
			//
			// TODO(roasbeef): only do this once link actually
			// fully settles?
			localHTLC := packet.incomingChanID == sourceHop
			if !localHTLC {
				s.fwdEventMtx.Lock()
				s.pendingFwdingEvents = append(
					s.pendingFwdingEvents,
					channeldb.ForwardingEvent{
						Timestamp:      time.Now(),
						IncomingChanID: circuit.Incoming.ChanID,
						OutgoingChanID: circuit.Outgoing.ChanID,
						AmtIn:          circuit.IncomingAmount,
						AmtOut:         circuit.OutgoingAmount,
					},
				)
				s.fwdEventMtx.Unlock()
			}
		}

		// A blank IncomingChanID in a circuit indicates that it is a pending
		// user-initiated payment.
		if packet.incomingChanID == sourceHop {
			return s.handleLocalDispatch(packet)
		}

		// Check to see that the source link is online before removing
		// the circuit.
		return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)

	default:
		return errors.New("wrong update type")
	}
}