// callback, which is called after the app rechecked the tx.
//
// The case where the app checks the tx for the first time is handled by the
// resCbFirstTime callback.
190229
func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) {
	switch r := res.Value.(type) {
	case *abci.Response_CheckTx:
		tx := req.GetCheckTx().Tx
		memTx := mem.recheckCursor.Value.(*mempoolTx)
		if !bytes.Equal(tx, memTx.tx) {
			panic(fmt.Sprintf(
				"Unexpected tx response from proxy during recheck\nExpected %X, got %X",
				memTx.tx,
				tx))
		}
		var postCheckErr error
		if mem.postCheck != nil {
			postCheckErr = mem.postCheck(tx, r.CheckTx)
		}
		if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
			// Good, nothing to do.
		} else {
			// Tx became invalidated due to newly committed block.
			mem.logger.Info("Tx is no longer valid", "tx", TxID(tx), "res", r, "err", postCheckErr)
			// NOTE: we remove tx from the cache because it might be good later
			mem.removeTx(tx, mem.recheckCursor, true)
		}
		if mem.recheckCursor == mem.recheckEnd {
			mem.recheckCursor = nil
		} else {
			mem.recheckCursor = mem.recheckCursor.Next()
		}
		if mem.recheckCursor == nil {
			// Done!
			atomic.StoreInt32(&mem.rechecking, 0)
			mem.logger.Info("Done rechecking txs")

			// incase the recheck removed all txs
			if mem.Size() > 0 {
				mem.notifyTxsAvailable()
			}
		}
	default:
		// ignore other messages
	}
}
249845
func (cp *CallbackProcessor) After(callbackName string) *CallbackProcessor {
	cp.after = callbackName
	return cp
}
173250
func (c *Conn) recv(notify func(string, []byte), done func(error)) {
	var resp Response
	var err error
	for {
		resp.reset()
		if err = c.codec.ReadResponse(&resp); err != nil {
			done(err)
			return
		}

		// Check if this is an RPC notification from the server.
		if resp.Method != "" {
			// Method represents the event that was triggered over the
			// Chrome DevTools Protocol. We do not expect to receive
			// RPC requests, if this was one, the ID field would be set.
			notify(resp.Method, resp.Args)
			continue
		}

		c.mu.Lock()
		call := c.pending[resp.ID]
		delete(c.pending, resp.ID)
		c.mu.Unlock()

		switch {
		case call == nil:
			// No pending call, this could mean there was an error during
			// send or the server sent an unexpected response.
			if enableDebug {
				log.Println("rpcc: no pending call: " + resp.String())
			}
		case resp.Error != nil:
			call.done(resp.Error)
		default:
			var err error
			if call.Reply != nil {
				if err = json.Unmarshal(resp.Result, call.Reply); err != nil {
					err = fmt.Errorf("rpcc: decoding %s: %s", call.Method, err.Error())
				}
			}
			call.done(err)
		}
	}
}
32290
func (tx *Tx) Rollback() error {
	if tx.funcd {
		panic("managed tx rollback not allowed")
	}
	if tx.db == nil {
		return ErrTxClosed
	}
	// The rollback func does the heavy lifting.
	if tx.writable {
		tx.rollbackInner()
	}
	// unlock the database for more transactions.
	tx.unlock()
	// Clear the db field to disable this transaction from future use.
	tx.db = nil
	return nil
}
30730
func TxPreCheck(state State) mempl.PreCheckFunc {
	maxDataBytes := types.MaxDataBytesUnknownEvidence(
		state.ConsensusParams.Block.MaxBytes,
		state.Validators.Size(),
	)
	return mempl.PreCheckAminoMaxBytes(maxDataBytes)
}
462050
func (tx *Tx) Rollback() error {
	_, err := tx.Exec("ROLLBACK")
	tx.close()
	return err
}
1205043
func (tx *Tx) Rollback() error {
	if tx.done {
		return ErrTxDone
	}
	defer tx.close()
	tx.dc.Lock()
	err := tx.txi.Rollback()
	tx.dc.Unlock()
	if err != driver.ErrBadConn {
		tx.closePrepared()
	}
	return err
}
1121164
func (s *Store) txnCheck(tx *memdb.Txn, idx uint64, op *structs.TxnCheckOp) (structs.TxnResults, error) {
	var entry *structs.HealthCheck
	var err error

	switch op.Verb {
	case api.CheckGet:
		_, entry, err = s.getNodeCheckTxn(tx, op.Check.Node, op.Check.CheckID)
		if entry == nil && err == nil {
			err = fmt.Errorf("check %q on node %q doesn't exist", op.Check.CheckID, op.Check.Node)
		}

	case api.CheckSet:
		err = s.ensureCheckTxn(tx, idx, &op.Check)
		if err == nil {
			_, entry, err = s.getNodeCheckTxn(tx, op.Check.Node, op.Check.CheckID)
		}

	case api.CheckCAS:
		var ok bool
		entry = &op.Check
		ok, err = s.ensureCheckCASTxn(tx, idx, entry)
		if !ok && err == nil {
			err = fmt.Errorf("failed to set check %q on node %q, index is stale", entry.CheckID, entry.Node)
			break
		}
		_, entry, err = s.getNodeCheckTxn(tx, op.Check.Node, op.Check.CheckID)

	case api.CheckDelete:
		err = s.deleteCheckTxn(tx, idx, op.Check.Node, op.Check.CheckID)

	case api.CheckDeleteCAS:
		var ok bool
		ok, err = s.deleteCheckCASTxn(tx, idx, op.Check.ModifyIndex, op.Check.Node, op.Check.CheckID)
		if !ok && err == nil {
			err = fmt.Errorf("failed to delete check %q on node %q, index is stale", op.Check.CheckID, op.Check.Node)
		}

	default:
		err = fmt.Errorf("unknown Check verb %q", op.Verb)
	}
	if err != nil {
		return nil, err
	}

	// For a GET we keep the value, otherwise we clone and blank out the
	// value (we have to clone so we don't modify the entry being used by
	// the state store).
	if entry != nil {
		if op.Verb == api.CheckGet {
			result := structs.TxnResult{Check: entry}
			return structs.TxnResults{&result}, nil
		}

		clone := entry.Clone()
		result := structs.TxnResult{Check: clone}
		return structs.TxnResults{&result}, nil
	}

	return nil, nil
}
274781
func (self *OauthAuthenticator) Callback(w http.ResponseWriter, req *http.Request) {
	sid := httputil.Q(req, `state`)
	code := httputil.Q(req, `code`)

	if sessionI, ok := oauthSessions.Load(sid); ok {
		if session, ok := sessionI.(*oauthSession); ok {
			if session.State == sid {
				if token, err := self.oauth2config.Exchange(oauth2.NoContext, code); err == nil {
					session.Code = code
					session.Token = token

					// give the client their session ID
					cookie := &http.Cookie{
						Name:     self.cookieName,
						Value:    session.State,
						Path:     `/`,
						Domain:   session.Domain,
						Secure:   (session.Scheme == `https`),
						HttpOnly: true,
						SameSite: http.SameSiteStrictMode,
					}

					log.Noticef("oauth token %v", token)

					if self.sessionDuration > 0 {
						cookie.Expires = time.Now().Add(self.sessionDuration)
					}

					http.SetCookie(w, cookie)
					http.Redirect(w, req, session.Path, http.StatusTemporaryRedirect)
				} else {
					http.Error(w, err.Error(), http.StatusBadRequest)
				}
			} else {
				http.Error(w, "Invalid OAuth2 session returned for callback", http.StatusBadRequest)
			}
		} else {
			http.Error(w, "Invalid OAuth2 session object", http.StatusBadRequest)
		}
	} else {
		http.Error(w, "OAuth2 session does not exist exists", http.StatusBadRequest)
	}
}
15986
func (s *linkServiceImpl) Callback(ctx context.Context, req *goa.RequestData, state string, code string) (string, error) {
	// validate known state
	knownReferrer, _, err := s.Services().AuthenticationProviderService().LoadReferrerAndResponseMode(ctx, state)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"state": state,
			"err":   err,
		}, "can't load referrer by state")
		return "", err
	}

	referrerURL, err := url.Parse(knownReferrer)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"code":           code,
			"state":          state,
			"known_referrer": knownReferrer,
			"err":            err,
		}, "failed to parse referrer")
		return "", err
	}

	identityID := referrerURL.Query().Get(identityIDParam)
	identityUUID, err := uuid.FromString(identityID)
	if err != nil {
		return "", err
	}

	forResource := referrerURL.Query().Get(forParam)

	oauthProvider, err := s.Factories().LinkingProviderFactory().NewLinkingProvider(ctx, identityUUID, rest.AbsoluteURL(req, "", nil), forResource)
	if err != nil {
		return "", err
	}

	providerToken, err := oauthProvider.Exchange(ctx, code)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"state": state,
			"code":  code,
			"err":   err,
		}, "exchange operation failed")
		return "", err
	}
	if providerToken.AccessToken == "" {
		log.Error(ctx, map[string]interface{}{
			"state":       state,
			"code":        code,
			"provider_id": oauthProvider.ID(),
		}, "access token return by provider is empty")
		return "", errors.New("access token return by provider is empty")
	}

	userProfile, err := oauthProvider.Profile(ctx, *providerToken)
	if err != nil {
		return "", err
	}
	err = s.ExecuteInTransaction(func() error {
		tokens, err := s.Repositories().ExternalTokens().LoadByProviderIDAndIdentityID(ctx, oauthProvider.ID(), identityUUID)
		if err != nil {
			return err
		}
		if len(tokens) > 0 {
			// It was re-linking. Overwrite the existing link.
			externalToken := tokens[0]
			externalToken.Token = providerToken.AccessToken
			externalToken.Username = userProfile.Username
			err = s.Repositories().ExternalTokens().Save(ctx, &externalToken)
			if err == nil {
				log.Info(ctx, map[string]interface{}{
					"provider_id":       oauthProvider.ID(),
					"identity_id":       identityID,
					"external_token_id": externalToken.ID,
				}, "An existing token found. Account re-linked & new token saved.")
			}
			return err
		}
		externalToken := token.ExternalToken{
			Token:      providerToken.AccessToken,
			IdentityID: identityUUID,
			Scope:      oauthProvider.Scopes(),
			ProviderID: oauthProvider.ID(),
			Username:   userProfile.Username,
		}
		err = s.Repositories().ExternalTokens().Create(ctx, &externalToken)
		if err == nil {
			log.Info(ctx, map[string]interface{}{
				"provider_id":       oauthProvider.ID(),
				"identity_id":       identityID,
				"external_token_id": externalToken.ID,
			}, "No old token found. Account linked & new token saved.")
		}
		return err
	})
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"state":       state,
			"code":        code,
			"provider_id": oauthProvider.ID(),
			"identity_id": identityID,
		}, "failed to save token")
		return "", err
	}

	nextResource := referrerURL.Query().Get(nextParam)
	if nextResource != "" {
		return s.ProviderLocation(ctx, req, identityID, nextResource, knownReferrer)
	}

	return knownReferrer, nil
}
798140
func _go_glib_callback(cbi *C.callback_info) {
	value, found := callback_contexts.Get(int(cbi.func_no))
	if !found {
		return
	}
	context := value.(*CallbackContext)
	t := context.f.Type()
	fargs := make([]reflect.Value, t.NumIn())
	if len(fargs) > 0 {
		fargs[0] = reflect.ValueOf(context)
	}
	ret := context.f.Call(fargs)
	if len(ret) > 0 {
		value := ret[0].Interface()
		switch value.(type) {
		case bool:
			bval := gbool(value.(bool))
			cbi.ret = unsafe.Pointer(&bval)
		case byte:
			bval := C.gchar(value.(byte))
			cbi.ret = unsafe.Pointer(&bval)
		case int:
			ival := C.int(value.(int))
			cbi.ret = unsafe.Pointer(&ival)
		case uint:
			uval := C.guint(value.(uint))
			cbi.ret = unsafe.Pointer(&uval)
		case float32:
			f32val := C.gfloat(value.(float32))
			cbi.ret = unsafe.Pointer(&f32val)
		case float64:
			f64val := C.gfloat(value.(float64))
			cbi.ret = unsafe.Pointer(&f64val)
		case string:
			cbi.ret = unsafe.Pointer(C.CString(value.(string)))
		default:
			if pv, ok := value.(*[0]uint8); ok {
				cbi.ret = unsafe.Pointer(pv)
			} else {
				av := reflect.ValueOf(value)
				if av.Kind() == reflect.Ptr {
					cbi.ret = unsafe.Pointer(av.Pointer())
				} else if av.CanAddr() {
					cbi.ret = unsafe.Pointer(av.UnsafeAddr())
				} else {
					cbi.ret = unsafe.Pointer(&value)
				}
			}
		}
	}
}
959341
func (t *Transaction) Rollback() error {
	t.dbmap.trace("rollback;")
	return t.Tx.Rollback()
}
400916
func (dc DefaultClock) AfterFunc(d time.Duration, f func()) Timer {
	return &defaultTimer{*time.AfterFunc(d, f)}
}
130451
func (c *LoginController) Callback(ctx *app.CallbackLoginContext) error {
	state := ctx.Params.Get("state")
	code := ctx.Params.Get("code")
	redirectURL := rest.AbsoluteURL(ctx.RequestData, client.CallbackLoginPath(), nil)
	redirectTo, err := c.app.AuthenticationProviderService().LoginCallback(ctx, state, code, redirectURL)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	ctx.ResponseData.Header().Set("Location", *redirectTo)
	return ctx.TemporaryRedirect()
}
643937
func (c *TxnCollector) AfterRunTransaction(dbName, modelUUID string, ops []txn.Op, err error) {
	for _, op := range ops {
		c.updateMetrics(dbName, op, err)
	}
}
850941
func Tx(db *sql.DB, txFunc func(*sql.Tx) error) (err error) {
	tx, err := db.Begin()
	if err != nil {
		return
	}
	defer func() {
		if p := recover(); p != nil {
			switch p := p.(type) {
			case error:
				err = p
			default:
				err = fmt.Errorf("%s", p)
			}
		}
		if err != nil {
			tx.Rollback()
			return
		}
		err = tx.Commit()
	}()
	return txFunc(tx)
}
83692
func (rd *Redirector) callback(w http.ResponseWriter, r *http.Request) (*auth.SSHLoginResponse, error) {
	if r.URL.Path != "/callback" {
		return nil, trace.NotFound("path not found")
	}

	// Decrypt ciphertext to get login response.
	plaintext, err := rd.key.Open([]byte(r.URL.Query().Get("response")))
	if err != nil {
		return nil, trace.BadParameter("failed to decrypt response: in %v, err: %v", r.URL.String(), err)
	}

	var re *auth.SSHLoginResponse
	err = json.Unmarshal(plaintext, &re)
	if err != nil {
		return nil, trace.BadParameter("failed to decrypt response: in %v, err: %v", r.URL.String(), err)
	}

	return re, nil
}