pool.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. package puddle
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/jackc/puddle/v2/internal/genstack"
  9. "golang.org/x/sync/semaphore"
  10. )
  11. const (
  12. resourceStatusConstructing = 0
  13. resourceStatusIdle = iota
  14. resourceStatusAcquired = iota
  15. resourceStatusHijacked = iota
  16. )
  17. // ErrClosedPool occurs on an attempt to acquire a connection from a closed pool
  18. // or a pool that is closed while the acquire is waiting.
  19. var ErrClosedPool = errors.New("closed pool")
  20. // ErrNotAvailable occurs on an attempt to acquire a resource from a pool
  21. // that is at maximum capacity and has no available resources.
  22. var ErrNotAvailable = errors.New("resource not available")
  23. // Constructor is a function called by the pool to construct a resource.
  24. type Constructor[T any] func(ctx context.Context) (res T, err error)
  25. // Destructor is a function called by the pool to destroy a resource.
  26. type Destructor[T any] func(res T)
  27. // Resource is the resource handle returned by acquiring from the pool.
  28. type Resource[T any] struct {
  29. value T
  30. pool *Pool[T]
  31. creationTime time.Time
  32. lastUsedNano int64
  33. poolResetCount int
  34. status byte
  35. }
  36. // Value returns the resource value.
  37. func (res *Resource[T]) Value() T {
  38. if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) {
  39. panic("tried to access resource that is not acquired or hijacked")
  40. }
  41. return res.value
  42. }
  43. // Release returns the resource to the pool. res must not be subsequently used.
  44. func (res *Resource[T]) Release() {
  45. if res.status != resourceStatusAcquired {
  46. panic("tried to release resource that is not acquired")
  47. }
  48. res.pool.releaseAcquiredResource(res, nanotime())
  49. }
  50. // ReleaseUnused returns the resource to the pool without updating when it was last used used. i.e. LastUsedNanotime
  51. // will not change. res must not be subsequently used.
  52. func (res *Resource[T]) ReleaseUnused() {
  53. if res.status != resourceStatusAcquired {
  54. panic("tried to release resource that is not acquired")
  55. }
  56. res.pool.releaseAcquiredResource(res, res.lastUsedNano)
  57. }
  58. // Destroy returns the resource to the pool for destruction. res must not be
  59. // subsequently used.
  60. func (res *Resource[T]) Destroy() {
  61. if res.status != resourceStatusAcquired {
  62. panic("tried to destroy resource that is not acquired")
  63. }
  64. go res.pool.destroyAcquiredResource(res)
  65. }
  66. // Hijack assumes ownership of the resource from the pool. Caller is responsible
  67. // for cleanup of resource value.
  68. func (res *Resource[T]) Hijack() {
  69. if res.status != resourceStatusAcquired {
  70. panic("tried to hijack resource that is not acquired")
  71. }
  72. res.pool.hijackAcquiredResource(res)
  73. }
  74. // CreationTime returns when the resource was created by the pool.
  75. func (res *Resource[T]) CreationTime() time.Time {
  76. if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) {
  77. panic("tried to access resource that is not acquired or hijacked")
  78. }
  79. return res.creationTime
  80. }
  81. // LastUsedNanotime returns when Release was last called on the resource measured in nanoseconds from an arbitrary time
  82. // (a monotonic time). Returns creation time if Release has never been called. This is only useful to compare with
  83. // other calls to LastUsedNanotime. In almost all cases, IdleDuration should be used instead.
  84. func (res *Resource[T]) LastUsedNanotime() int64 {
  85. if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) {
  86. panic("tried to access resource that is not acquired or hijacked")
  87. }
  88. return res.lastUsedNano
  89. }
  90. // IdleDuration returns the duration since Release was last called on the resource. This is equivalent to subtracting
  91. // LastUsedNanotime to the current nanotime.
  92. func (res *Resource[T]) IdleDuration() time.Duration {
  93. if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) {
  94. panic("tried to access resource that is not acquired or hijacked")
  95. }
  96. return time.Duration(nanotime() - res.lastUsedNano)
  97. }
  98. // Pool is a concurrency-safe resource pool.
  99. type Pool[T any] struct {
  100. // mux is the pool internal lock. Any modification of shared state of
  101. // the pool (but Acquires of acquireSem) must be performed only by
  102. // holder of the lock. Long running operations are not allowed when mux
  103. // is held.
  104. mux sync.Mutex
  105. // acquireSem provides an allowance to acquire a resource.
  106. //
  107. // Releases are allowed only when caller holds mux. Acquires have to
  108. // happen before mux is locked (doesn't apply to semaphore.TryAcquire in
  109. // AcquireAllIdle).
  110. acquireSem *semaphore.Weighted
  111. destructWG sync.WaitGroup
  112. allResources resList[T]
  113. idleResources *genstack.GenStack[*Resource[T]]
  114. constructor Constructor[T]
  115. destructor Destructor[T]
  116. maxSize int32
  117. acquireCount int64
  118. acquireDuration time.Duration
  119. emptyAcquireCount int64
  120. emptyAcquireWaitTime time.Duration
  121. canceledAcquireCount atomic.Int64
  122. resetCount int
  123. baseAcquireCtx context.Context
  124. cancelBaseAcquireCtx context.CancelFunc
  125. closed bool
  126. }
  127. type Config[T any] struct {
  128. Constructor Constructor[T]
  129. Destructor Destructor[T]
  130. MaxSize int32
  131. }
  132. // NewPool creates a new pool. Returns an error iff MaxSize is less than 1.
  133. func NewPool[T any](config *Config[T]) (*Pool[T], error) {
  134. if config.MaxSize < 1 {
  135. return nil, errors.New("MaxSize must be >= 1")
  136. }
  137. baseAcquireCtx, cancelBaseAcquireCtx := context.WithCancel(context.Background())
  138. return &Pool[T]{
  139. acquireSem: semaphore.NewWeighted(int64(config.MaxSize)),
  140. idleResources: genstack.NewGenStack[*Resource[T]](),
  141. maxSize: config.MaxSize,
  142. constructor: config.Constructor,
  143. destructor: config.Destructor,
  144. baseAcquireCtx: baseAcquireCtx,
  145. cancelBaseAcquireCtx: cancelBaseAcquireCtx,
  146. }, nil
  147. }
  148. // Close destroys all resources in the pool and rejects future Acquire calls.
  149. // Blocks until all resources are returned to pool and destroyed.
  150. func (p *Pool[T]) Close() {
  151. defer p.destructWG.Wait()
  152. p.mux.Lock()
  153. defer p.mux.Unlock()
  154. if p.closed {
  155. return
  156. }
  157. p.closed = true
  158. p.cancelBaseAcquireCtx()
  159. for res, ok := p.idleResources.Pop(); ok; res, ok = p.idleResources.Pop() {
  160. p.allResources.remove(res)
  161. go p.destructResourceValue(res.value)
  162. }
  163. }
  164. // Stat is a snapshot of Pool statistics.
  165. type Stat struct {
  166. constructingResources int32
  167. acquiredResources int32
  168. idleResources int32
  169. maxResources int32
  170. acquireCount int64
  171. acquireDuration time.Duration
  172. emptyAcquireCount int64
  173. emptyAcquireWaitTime time.Duration
  174. canceledAcquireCount int64
  175. }
  176. // TotalResources returns the total number of resources currently in the pool.
  177. // The value is the sum of ConstructingResources, AcquiredResources, and
  178. // IdleResources.
  179. func (s *Stat) TotalResources() int32 {
  180. return s.constructingResources + s.acquiredResources + s.idleResources
  181. }
  182. // ConstructingResources returns the number of resources with construction in progress in
  183. // the pool.
  184. func (s *Stat) ConstructingResources() int32 {
  185. return s.constructingResources
  186. }
  187. // AcquiredResources returns the number of currently acquired resources in the pool.
  188. func (s *Stat) AcquiredResources() int32 {
  189. return s.acquiredResources
  190. }
  191. // IdleResources returns the number of currently idle resources in the pool.
  192. func (s *Stat) IdleResources() int32 {
  193. return s.idleResources
  194. }
  195. // MaxResources returns the maximum size of the pool.
  196. func (s *Stat) MaxResources() int32 {
  197. return s.maxResources
  198. }
  199. // AcquireCount returns the cumulative count of successful acquires from the pool.
  200. func (s *Stat) AcquireCount() int64 {
  201. return s.acquireCount
  202. }
  203. // AcquireDuration returns the total duration of all successful acquires from
  204. // the pool.
  205. func (s *Stat) AcquireDuration() time.Duration {
  206. return s.acquireDuration
  207. }
  208. // EmptyAcquireCount returns the cumulative count of successful acquires from the pool
  209. // that waited for a resource to be released or constructed because the pool was
  210. // empty.
  211. func (s *Stat) EmptyAcquireCount() int64 {
  212. return s.emptyAcquireCount
  213. }
  214. // EmptyAcquireWaitTime returns the cumulative time waited for successful acquires
  215. // from the pool for a resource to be released or constructed because the pool was
  216. // empty.
  217. func (s *Stat) EmptyAcquireWaitTime() time.Duration {
  218. return s.emptyAcquireWaitTime
  219. }
  220. // CanceledAcquireCount returns the cumulative count of acquires from the pool
  221. // that were canceled by a context.
  222. func (s *Stat) CanceledAcquireCount() int64 {
  223. return s.canceledAcquireCount
  224. }
  225. // Stat returns the current pool statistics.
  226. func (p *Pool[T]) Stat() *Stat {
  227. p.mux.Lock()
  228. defer p.mux.Unlock()
  229. s := &Stat{
  230. maxResources: p.maxSize,
  231. acquireCount: p.acquireCount,
  232. emptyAcquireCount: p.emptyAcquireCount,
  233. emptyAcquireWaitTime: p.emptyAcquireWaitTime,
  234. canceledAcquireCount: p.canceledAcquireCount.Load(),
  235. acquireDuration: p.acquireDuration,
  236. }
  237. for _, res := range p.allResources {
  238. switch res.status {
  239. case resourceStatusConstructing:
  240. s.constructingResources += 1
  241. case resourceStatusIdle:
  242. s.idleResources += 1
  243. case resourceStatusAcquired:
  244. s.acquiredResources += 1
  245. }
  246. }
  247. return s
  248. }
  249. // tryAcquireIdleResource checks if there is any idle resource. If there is
  250. // some, this method removes it from idle list and returns it. If the idle pool
  251. // is empty, this method returns nil and doesn't modify the idleResources slice.
  252. //
  253. // WARNING: Caller of this method must hold the pool mutex!
  254. func (p *Pool[T]) tryAcquireIdleResource() *Resource[T] {
  255. res, ok := p.idleResources.Pop()
  256. if !ok {
  257. return nil
  258. }
  259. res.status = resourceStatusAcquired
  260. return res
  261. }
  262. // createNewResource creates a new resource and inserts it into list of pool
  263. // resources.
  264. //
  265. // WARNING: Caller of this method must hold the pool mutex!
  266. func (p *Pool[T]) createNewResource() *Resource[T] {
  267. res := &Resource[T]{
  268. pool: p,
  269. creationTime: time.Now(),
  270. lastUsedNano: nanotime(),
  271. poolResetCount: p.resetCount,
  272. status: resourceStatusConstructing,
  273. }
  274. p.allResources.append(res)
  275. p.destructWG.Add(1)
  276. return res
  277. }
  278. // Acquire gets a resource from the pool. If no resources are available and the pool is not at maximum capacity it will
  279. // create a new resource. If the pool is at maximum capacity it will block until a resource is available. ctx can be
  280. // used to cancel the Acquire.
  281. //
  282. // If Acquire creates a new resource the resource constructor function will receive a context that delegates Value() to
  283. // ctx. Canceling ctx will cause Acquire to return immediately but it will not cancel the resource creation. This avoids
  284. // the problem of it being impossible to create resources when the time to create a resource is greater than any one
  285. // caller of Acquire is willing to wait.
  286. func (p *Pool[T]) Acquire(ctx context.Context) (_ *Resource[T], err error) {
  287. select {
  288. case <-ctx.Done():
  289. p.canceledAcquireCount.Add(1)
  290. return nil, ctx.Err()
  291. default:
  292. }
  293. return p.acquire(ctx)
  294. }
  295. // acquire is a continuation of Acquire function that doesn't check context
  296. // validity.
  297. //
  298. // This function exists solely only for benchmarking purposes.
  299. func (p *Pool[T]) acquire(ctx context.Context) (*Resource[T], error) {
  300. startNano := nanotime()
  301. var waitedForLock bool
  302. if !p.acquireSem.TryAcquire(1) {
  303. waitedForLock = true
  304. err := p.acquireSem.Acquire(ctx, 1)
  305. if err != nil {
  306. p.canceledAcquireCount.Add(1)
  307. return nil, err
  308. }
  309. }
  310. p.mux.Lock()
  311. if p.closed {
  312. p.acquireSem.Release(1)
  313. p.mux.Unlock()
  314. return nil, ErrClosedPool
  315. }
  316. // If a resource is available in the pool.
  317. if res := p.tryAcquireIdleResource(); res != nil {
  318. waitTime := time.Duration(nanotime() - startNano)
  319. if waitedForLock {
  320. p.emptyAcquireCount += 1
  321. p.emptyAcquireWaitTime += waitTime
  322. }
  323. p.acquireCount += 1
  324. p.acquireDuration += waitTime
  325. p.mux.Unlock()
  326. return res, nil
  327. }
  328. if len(p.allResources) >= int(p.maxSize) {
  329. // Unreachable code.
  330. panic("bug: semaphore allowed more acquires than pool allows")
  331. }
  332. // The resource is not idle, but there is enough space to create one.
  333. res := p.createNewResource()
  334. p.mux.Unlock()
  335. res, err := p.initResourceValue(ctx, res)
  336. if err != nil {
  337. return nil, err
  338. }
  339. p.mux.Lock()
  340. defer p.mux.Unlock()
  341. p.emptyAcquireCount += 1
  342. p.acquireCount += 1
  343. waitTime := time.Duration(nanotime() - startNano)
  344. p.acquireDuration += waitTime
  345. p.emptyAcquireWaitTime += waitTime
  346. return res, nil
  347. }
  348. func (p *Pool[T]) initResourceValue(ctx context.Context, res *Resource[T]) (*Resource[T], error) {
  349. // Create the resource in a goroutine to immediately return from Acquire
  350. // if ctx is canceled without also canceling the constructor.
  351. //
  352. // See:
  353. // - https://github.com/jackc/pgx/issues/1287
  354. // - https://github.com/jackc/pgx/issues/1259
  355. constructErrChan := make(chan error)
  356. go func() {
  357. constructorCtx := newValueCancelCtx(ctx, p.baseAcquireCtx)
  358. value, err := p.constructor(constructorCtx)
  359. if err != nil {
  360. p.mux.Lock()
  361. p.allResources.remove(res)
  362. p.destructWG.Done()
  363. // The resource won't be acquired because its
  364. // construction failed. We have to allow someone else to
  365. // take that resouce.
  366. p.acquireSem.Release(1)
  367. p.mux.Unlock()
  368. select {
  369. case constructErrChan <- err:
  370. case <-ctx.Done():
  371. // The caller is cancelled, so no-one awaits the
  372. // error. This branch avoid goroutine leak.
  373. }
  374. return
  375. }
  376. // The resource is already in p.allResources where it might be read. So we need to acquire the lock to update its
  377. // status.
  378. p.mux.Lock()
  379. res.value = value
  380. res.status = resourceStatusAcquired
  381. p.mux.Unlock()
  382. // This select works because the channel is unbuffered.
  383. select {
  384. case constructErrChan <- nil:
  385. case <-ctx.Done():
  386. p.releaseAcquiredResource(res, res.lastUsedNano)
  387. }
  388. }()
  389. select {
  390. case <-ctx.Done():
  391. p.canceledAcquireCount.Add(1)
  392. return nil, ctx.Err()
  393. case err := <-constructErrChan:
  394. if err != nil {
  395. return nil, err
  396. }
  397. return res, nil
  398. }
  399. }
  400. // TryAcquire gets a resource from the pool if one is immediately available. If not, it returns ErrNotAvailable. If no
  401. // resources are available but the pool has room to grow, a resource will be created in the background. ctx is only
  402. // used to cancel the background creation.
  403. func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) {
  404. if !p.acquireSem.TryAcquire(1) {
  405. return nil, ErrNotAvailable
  406. }
  407. p.mux.Lock()
  408. defer p.mux.Unlock()
  409. if p.closed {
  410. p.acquireSem.Release(1)
  411. return nil, ErrClosedPool
  412. }
  413. // If a resource is available now
  414. if res := p.tryAcquireIdleResource(); res != nil {
  415. p.acquireCount += 1
  416. return res, nil
  417. }
  418. if len(p.allResources) >= int(p.maxSize) {
  419. // Unreachable code.
  420. panic("bug: semaphore allowed more acquires than pool allows")
  421. }
  422. res := p.createNewResource()
  423. go func() {
  424. value, err := p.constructor(ctx)
  425. p.mux.Lock()
  426. defer p.mux.Unlock()
  427. // We have to create the resource and only then release the
  428. // semaphore - For the time being there is no resource that
  429. // someone could acquire.
  430. defer p.acquireSem.Release(1)
  431. if err != nil {
  432. p.allResources.remove(res)
  433. p.destructWG.Done()
  434. return
  435. }
  436. res.value = value
  437. res.status = resourceStatusIdle
  438. p.idleResources.Push(res)
  439. }()
  440. return nil, ErrNotAvailable
  441. }
  442. // acquireSemAll tries to acquire num free tokens from sem. This function is
  443. // guaranteed to acquire at least the lowest number of tokens that has been
  444. // available in the semaphore during runtime of this function.
  445. //
  446. // For the time being, semaphore doesn't allow to acquire all tokens atomically
  447. // (see https://github.com/golang/sync/pull/19). We simulate this by trying all
  448. // powers of 2 that are less or equal to num.
  449. //
  450. // For example, let's immagine we have 19 free tokens in the semaphore which in
  451. // total has 24 tokens (i.e. the maxSize of the pool is 24 resources). Then if
  452. // num is 24, the log2Uint(24) is 4 and we try to acquire 16, 8, 4, 2 and 1
  453. // tokens. Out of those, the acquire of 16, 2 and 1 tokens will succeed.
  454. //
  455. // Naturally, Acquires and Releases of the semaphore might take place
  456. // concurrently. For this reason, it's not guaranteed that absolutely all free
  457. // tokens in the semaphore will be acquired. But it's guaranteed that at least
  458. // the minimal number of tokens that has been present over the whole process
  459. // will be acquired. This is sufficient for the use-case we have in this
  460. // package.
  461. //
  462. // TODO: Replace this with acquireSem.TryAcquireAll() if it gets to
  463. // upstream. https://github.com/golang/sync/pull/19
  464. func acquireSemAll(sem *semaphore.Weighted, num int) int {
  465. if sem.TryAcquire(int64(num)) {
  466. return num
  467. }
  468. var acquired int
  469. for i := int(log2Int(num)); i >= 0; i-- {
  470. val := 1 << i
  471. if sem.TryAcquire(int64(val)) {
  472. acquired += val
  473. }
  474. }
  475. return acquired
  476. }
  477. // AcquireAllIdle acquires all currently idle resources. Its intended use is for
  478. // health check and keep-alive functionality. It does not update pool
  479. // statistics.
  480. func (p *Pool[T]) AcquireAllIdle() []*Resource[T] {
  481. p.mux.Lock()
  482. defer p.mux.Unlock()
  483. if p.closed {
  484. return nil
  485. }
  486. numIdle := p.idleResources.Len()
  487. if numIdle == 0 {
  488. return nil
  489. }
  490. // In acquireSemAll we use only TryAcquire and not Acquire. Because
  491. // TryAcquire cannot block, the fact that we hold mutex locked and try
  492. // to acquire semaphore cannot result in dead-lock.
  493. //
  494. // Because the mutex is locked, no parallel Release can run. This
  495. // implies that the number of tokens can only decrease because some
  496. // Acquire/TryAcquire call can consume the semaphore token. Consequently
  497. // acquired is always less or equal to numIdle. Moreover if acquired <
  498. // numIdle, then there are some parallel Acquire/TryAcquire calls that
  499. // will take the remaining idle connections.
  500. acquired := acquireSemAll(p.acquireSem, numIdle)
  501. idle := make([]*Resource[T], acquired)
  502. for i := range idle {
  503. res, _ := p.idleResources.Pop()
  504. res.status = resourceStatusAcquired
  505. idle[i] = res
  506. }
  507. // We have to bump the generation to ensure that Acquire/TryAcquire
  508. // calls running in parallel (those which caused acquired < numIdle)
  509. // will consume old connections and not freshly released connections
  510. // instead.
  511. p.idleResources.NextGen()
  512. return idle
  513. }
  514. // CreateResource constructs a new resource without acquiring it. It goes straight in the IdlePool. If the pool is full
  515. // it returns an error. It can be useful to maintain warm resources under little load.
  516. func (p *Pool[T]) CreateResource(ctx context.Context) error {
  517. if !p.acquireSem.TryAcquire(1) {
  518. return ErrNotAvailable
  519. }
  520. p.mux.Lock()
  521. if p.closed {
  522. p.acquireSem.Release(1)
  523. p.mux.Unlock()
  524. return ErrClosedPool
  525. }
  526. if len(p.allResources) >= int(p.maxSize) {
  527. p.acquireSem.Release(1)
  528. p.mux.Unlock()
  529. return ErrNotAvailable
  530. }
  531. res := p.createNewResource()
  532. p.mux.Unlock()
  533. value, err := p.constructor(ctx)
  534. p.mux.Lock()
  535. defer p.mux.Unlock()
  536. defer p.acquireSem.Release(1)
  537. if err != nil {
  538. p.allResources.remove(res)
  539. p.destructWG.Done()
  540. return err
  541. }
  542. res.value = value
  543. res.status = resourceStatusIdle
  544. // If closed while constructing resource then destroy it and return an error
  545. if p.closed {
  546. go p.destructResourceValue(res.value)
  547. return ErrClosedPool
  548. }
  549. p.idleResources.Push(res)
  550. return nil
  551. }
  552. // Reset destroys all resources, but leaves the pool open. It is intended for use when an error is detected that would
  553. // disrupt all resources (such as a network interruption or a server state change).
  554. //
  555. // It is safe to reset a pool while resources are checked out. Those resources will be destroyed when they are returned
  556. // to the pool.
  557. func (p *Pool[T]) Reset() {
  558. p.mux.Lock()
  559. defer p.mux.Unlock()
  560. p.resetCount++
  561. for res, ok := p.idleResources.Pop(); ok; res, ok = p.idleResources.Pop() {
  562. p.allResources.remove(res)
  563. go p.destructResourceValue(res.value)
  564. }
  565. }
  566. // releaseAcquiredResource returns res to the the pool.
  567. func (p *Pool[T]) releaseAcquiredResource(res *Resource[T], lastUsedNano int64) {
  568. p.mux.Lock()
  569. defer p.mux.Unlock()
  570. defer p.acquireSem.Release(1)
  571. if p.closed || res.poolResetCount != p.resetCount {
  572. p.allResources.remove(res)
  573. go p.destructResourceValue(res.value)
  574. } else {
  575. res.lastUsedNano = lastUsedNano
  576. res.status = resourceStatusIdle
  577. p.idleResources.Push(res)
  578. }
  579. }
  580. // Remove removes res from the pool and closes it. If res is not part of the
  581. // pool Remove will panic.
  582. func (p *Pool[T]) destroyAcquiredResource(res *Resource[T]) {
  583. p.destructResourceValue(res.value)
  584. p.mux.Lock()
  585. defer p.mux.Unlock()
  586. defer p.acquireSem.Release(1)
  587. p.allResources.remove(res)
  588. }
  589. func (p *Pool[T]) hijackAcquiredResource(res *Resource[T]) {
  590. p.mux.Lock()
  591. defer p.mux.Unlock()
  592. defer p.acquireSem.Release(1)
  593. p.allResources.remove(res)
  594. res.status = resourceStatusHijacked
  595. p.destructWG.Done() // not responsible for destructing hijacked resources
  596. }
  597. func (p *Pool[T]) destructResourceValue(value T) {
  598. p.destructor(value)
  599. p.destructWG.Done()
  600. }