-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[sync] T4086 Avoid computed updates through unavailable tables T4086 #3219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
12 changes: 12 additions & 0 deletions
12
apps/nestjs-backend/src/distributed-lock/distributed-lock.module.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { Module } from '@nestjs/common'; | ||
| import { DistributedLockService } from './distributed-lock.service'; | ||
|
|
||
| /** | ||
| * Provides {@link DistributedLockService}. Import it into any feature module | ||
| * that needs to guard startup seeding or other once-per-deployment work. | ||
| */ | ||
| @Module({ | ||
| providers: [DistributedLockService], | ||
| exports: [DistributedLockService], | ||
| }) | ||
| export class DistributedLockModule {} |
100 changes: 100 additions & 0 deletions
100
apps/nestjs-backend/src/distributed-lock/distributed-lock.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import type { ConfigService } from '@nestjs/config'; | ||
| import { afterEach, describe, expect, it, vi } from 'vitest'; | ||
| import type { CacheService } from '../cache/cache.service'; | ||
| import { DistributedLockService } from './distributed-lock.service'; | ||
|
|
||
| describe('DistributedLockService', () => { | ||
| const cache = { setnx: vi.fn(), get: vi.fn(), del: vi.fn() }; | ||
| const config = { get: vi.fn() }; | ||
| const newService = () => | ||
| new DistributedLockService( | ||
| cache as unknown as CacheService, | ||
| config as unknown as ConfigService | ||
| ); | ||
|
|
||
| afterEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('with Redis', () => { | ||
| const useRedis = () => config.get.mockReturnValue({ provider: 'redis' }); | ||
|
|
||
| it('runs the task when the lock is acquired', async () => { | ||
| useRedis(); | ||
| cache.setnx.mockResolvedValue(true); | ||
| const task = vi.fn().mockResolvedValue(undefined); | ||
|
|
||
| const ran = await newService().runExclusive('seed', 60, task); | ||
|
|
||
| expect(ran).toBe(true); | ||
| expect(cache.setnx).toHaveBeenCalledWith('lock:seed', expect.any(String), 60); | ||
| expect(task).toHaveBeenCalledOnce(); | ||
| }); | ||
|
|
||
| it('skips the task when another instance holds the lock', async () => { | ||
| useRedis(); | ||
| cache.setnx.mockResolvedValue(false); | ||
| const task = vi.fn(); | ||
|
|
||
| const ran = await newService().runExclusive('seed', 60, task); | ||
|
|
||
| expect(ran).toBe(false); | ||
| expect(task).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('releases the lock it owns after the task', async () => { | ||
| useRedis(); | ||
| cache.setnx.mockResolvedValue(true); | ||
| // Mirror Redis: `get` returns the value `setnx` stored. | ||
| cache.get.mockImplementation(async () => cache.setnx.mock.calls[0]?.[1]); | ||
|
|
||
| await newService().runExclusive('seed', 60, vi.fn().mockResolvedValue(undefined)); | ||
|
|
||
| expect(cache.del).toHaveBeenCalledWith('lock:seed'); | ||
| }); | ||
|
|
||
| it('releases the lock even when the task throws', async () => { | ||
| useRedis(); | ||
| cache.setnx.mockResolvedValue(true); | ||
| cache.get.mockImplementation(async () => cache.setnx.mock.calls[0]?.[1]); | ||
| const task = vi.fn().mockRejectedValue(new Error('boom')); | ||
|
|
||
| await expect(newService().runExclusive('seed', 60, task)).rejects.toThrow('boom'); | ||
| expect(cache.del).toHaveBeenCalledWith('lock:seed'); | ||
| }); | ||
|
|
||
| it('does not release a lock owned by another instance', async () => { | ||
| useRedis(); | ||
| cache.setnx.mockResolvedValue(true); | ||
| cache.get.mockResolvedValue('another-instance'); | ||
|
|
||
| await newService().runExclusive('seed', 60, vi.fn().mockResolvedValue(undefined)); | ||
|
|
||
| expect(cache.del).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('runs the task anyway when acquiring the lock errors', async () => { | ||
| useRedis(); | ||
| cache.setnx.mockRejectedValue(new Error('redis down')); | ||
| const task = vi.fn().mockResolvedValue(undefined); | ||
|
|
||
| const ran = await newService().runExclusive('seed', 60, task); | ||
|
|
||
| expect(ran).toBe(true); | ||
| expect(task).toHaveBeenCalledOnce(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('without Redis', () => { | ||
| it('runs the task without acquiring a lock', async () => { | ||
| config.get.mockReturnValue({ provider: 'memory' }); | ||
| const task = vi.fn().mockResolvedValue(undefined); | ||
|
|
||
| const ran = await newService().runExclusive('seed', 60, task); | ||
|
|
||
| expect(ran).toBe(true); | ||
| expect(cache.setnx).not.toHaveBeenCalled(); | ||
| expect(task).toHaveBeenCalledOnce(); | ||
| }); | ||
| }); | ||
| }); |
83 changes: 83 additions & 0 deletions
83
apps/nestjs-backend/src/distributed-lock/distributed-lock.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import { Injectable, Logger } from '@nestjs/common'; | ||
| import { ConfigService } from '@nestjs/config'; | ||
| import { CacheService } from '../cache/cache.service'; | ||
| import type { ICacheConfig } from '../configs/cache.config'; | ||
|
|
||
| /** | ||
| * Best-effort distributed lock backed by Redis (`SET NX`). | ||
| * | ||
| * Lets a caller run a critical section on exactly one instance across a | ||
| * multi-pod deployment. Without Redis there is no shared store, so the lock | ||
| * degrades to a no-op and every instance proceeds — callers must therefore | ||
| * keep the guarded work idempotent. | ||
| */ | ||
| @Injectable() | ||
| export class DistributedLockService { | ||
| private readonly logger = new Logger(DistributedLockService.name); | ||
|
|
||
| /** Unique per process — identifies the locks this instance owns. */ | ||
| private readonly owner = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`; | ||
|
|
||
| constructor( | ||
| private readonly cacheService: CacheService, | ||
| private readonly configService: ConfigService | ||
| ) {} | ||
|
|
||
| /** | ||
| * Run `task` while holding the lock named `name`, so only one instance runs | ||
| * it at a time. If another instance holds the lock, `task` is skipped. The | ||
| * lock is released afterwards and also auto-expires after `ttlSeconds`. | ||
| * | ||
| * @returns `true` if `task` ran, `false` if it was skipped. | ||
| */ | ||
| async runExclusive( | ||
| name: string, | ||
| ttlSeconds: number, | ||
| task: () => Promise<void> | ||
| ): Promise<boolean> { | ||
| const key = `lock:${name}` as const; | ||
|
|
||
| if (!(await this.acquire(key, ttlSeconds))) { | ||
| this.logger.debug(`Lock "${name}" held by another instance, skipping`); | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| await task(); | ||
| } finally { | ||
| await this.release(key); | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| private get usesRedis(): boolean { | ||
| return this.configService.get<ICacheConfig>('cache')?.provider === 'redis'; | ||
| } | ||
|
|
||
| private async acquire(key: `lock:${string}`, ttlSeconds: number): Promise<boolean> { | ||
| // No Redis — no shared store to lock against; let the caller proceed. | ||
| if (!this.usesRedis) { | ||
| return true; | ||
| } | ||
| try { | ||
| return await this.cacheService.setnx(key, this.owner, ttlSeconds); | ||
| } catch (error) { | ||
| this.logger.warn(`Failed to acquire lock "${key}", proceeding anyway`, error); | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| private async release(key: `lock:${string}`): Promise<void> { | ||
| if (!this.usesRedis) { | ||
| return; | ||
| } | ||
| try { | ||
| // Only release a lock this instance still owns. | ||
| if ((await this.cacheService.get(key)) === this.owner) { | ||
| await this.cacheService.del(key); | ||
| } | ||
| } catch (error) { | ||
| this.logger.warn(`Failed to release lock "${key}"`, error); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export { DistributedLockModule } from './distributed-lock.module'; | ||
| export { DistributedLockService } from './distributed-lock.service'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
get+delsequence is not atomic, so a lock can be deleted after ownership changes: if this process reads its own owner value, then the key expires and another instance acquires it beforedelruns, the subsequentdelremoves the new owner’s lock. That breaks mutual exclusion and can allow overlapping critical sections when tasks run near TTL boundaries. Use an atomic compare-and-delete (e.g., a Lua script) instead of separate calls.Useful? React with 👍 / 👎.