pingcap / pingcap/tidb

Introduce `Session.SetSession` to set the states of a session from pool.

Open
#60,507 0 comments 0 reactions 0 assignees View on GitHub
type/enhancement
Dominant language
Go
Stars
40.5k
Forks
6.2k
PR merge metrics
PR metrics pending

Description

## Enhancement

When managing internal system sessions, it is often necessary to configure their internal states, such as system variables. To prevent data corruption, the caller is responsible for resetting these states before returning the session to the pool. However, implementing this requirement correctly can be challenging. Callers may inadvertently forget to reset states or leave some states unrestored due to bugs, leading to potential issues.

We propose adding a new method, `SetSession`, to the `syssession::Session` type. The method is defined as follows:

```go
func (s *Session) SetSession(action SetStateAction, otherActions ...SetStateAction) (func() error, error) {
...
}
```

An example of usage:

```go
// s has a type `*Session`
s, err := pool.Get()
if err != nil {
// handle error ...
}

restore, err := s.SetSession(
SetSysVar("tidb_distsql_scan_concurrency", "1"),
SetSysVarToDefault("time_zone"),
)
if err != nil {
// handle error ...
}

// restore is used to reset the internal session to the state before `SetSession` calls.
err := restore()
if err != nil {
// handle error ...
}

// When putting back a session, all modified states will be set to the default.
pool.Put(s)
```

The caller can specify one or more actions here. For the above example, it sets the system variable `tidb_distsql_scan_concurrency` to `1` and then sets the time zone same with the global settings.

`SetSession` also returns an extra function to restore the session state. If you call this function, it will reset the session to the state before `SetSession` calls (NOT the default state).

When putting back a session with `pool.Put`. The pool will reset all modified states to the default value (That is different with restore function).

SetSession trys to guarantee the atomic, that is, if fails to set one of the state, it will rollback all other states in the same call. If it fails to rollback, the session will be marked as avoid-to-reuse.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.