mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 03:44:27 +00:00
feat(quota): add 2-level database-backed resource quota system (#318)
* feat(quota): add database-backed resource quota system * feat(webui): add resource quota management in team settings (#319) * feat(webui): add resource quota settings in team management * refactor(webui): update quotas list to full row layout and restrict skill/mcp to select list * feat(quota): refactor quota system to 2-level rules and records * fix(webui): fix overflow and scroll area in quota usage records dialog * fix(webui): ensure quota records scroll area has explicit max height * feat(webui): improve quota cards interaction and restrict editable fields in edit mode * fix(quota): serialize initial records, validate merged updates, and reset on dimension changes (#320) * feat(quota): replace network quota with agent tools quota (#321) * feat(webui): show remaining time until next refresh in quota usage records * fix(webui): rename bash quota resource to Agent Bash Calls * refactor(quota): remove unused reserved field from quota records * refactor(quota): remove quota rule cache (#322)
This commit is contained in:
@@ -24,6 +24,7 @@ export async function dedupeSymlinksToTarget(
|
||||
): Promise<void> {
|
||||
const existingSymlinks = await tx.asset.findMany({
|
||||
where: { targetId: { in: targetIds }, type: AssetType.symlink },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
if (existingSymlinks.length === 0) return
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ export enum ResourceType {
|
||||
Invite = 'invite',
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
QuotaRule = 'quotaRule',
|
||||
}
|
||||
|
||||
export interface AuthzRequest {
|
||||
@@ -259,6 +260,15 @@ export class AuthzService {
|
||||
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
|
||||
}
|
||||
|
||||
case ResourceType.QuotaRule: {
|
||||
const rule = await prisma.quotaRule.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!rule) throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
return { teamId: rule.teamId }
|
||||
}
|
||||
|
||||
default:
|
||||
throw new HTTPException(403, { message: `Unsupported resource type: ${type}` })
|
||||
}
|
||||
|
||||
@@ -26,3 +26,4 @@ export * from './ai-usage/ai-usage'
|
||||
export * from './watermark/watermark'
|
||||
export * from './gotenberg/gotenberg'
|
||||
export * from './mcp/mcp-service'
|
||||
export * from './quota/quota-service'
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { auth } from '@modelcontextprotocol/client'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { prisma, type TeamMemberRole } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import type {
|
||||
CreateMcpServerRequest,
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
} from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
|
||||
import { buildDirectTools, isDirectTool } from './mcp-direct-tools'
|
||||
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
|
||||
@@ -529,6 +530,32 @@ export class McpService {
|
||||
return { ok: false, content: [{ type: 'text', text: denied }] }
|
||||
}
|
||||
|
||||
let role: TeamMemberRole | null | undefined = undefined
|
||||
if (ctx?.teamId && ctx?.userId) {
|
||||
role = await resolveEffectiveRole(ctx.teamId, ctx.projectId, ctx.userId)
|
||||
}
|
||||
|
||||
if (ctx?.teamId) {
|
||||
try {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: ctx.teamId,
|
||||
userId: ctx.userId,
|
||||
role,
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: serverId, mcpServerId: serverId },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return {
|
||||
ok: false,
|
||||
content: [{ type: 'text', text: `Quota exceeded: ${message}` }],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const outcome = await this.ensureConnected(serverId)
|
||||
if (outcome.status === 'needs-auth') {
|
||||
return {
|
||||
@@ -555,6 +582,24 @@ export class McpService {
|
||||
|
||||
try {
|
||||
const result = await this.manager.callTool(serverId, toolName, args)
|
||||
|
||||
if (ctx?.teamId) {
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: ctx.teamId,
|
||||
userId: ctx.userId,
|
||||
role,
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: serverId, mcpServerId: serverId },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for MCP tool call')
|
||||
}
|
||||
}
|
||||
|
||||
if (result.isError) {
|
||||
const text = result.content.map((c) => ('text' in c ? c.text : '[image]')).join('\n')
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,769 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { quotaService, QuotaExceededError, wildcardToRegex } from './quota-service'
|
||||
|
||||
describe('QuotaRule Wildcard Matchers', () => {
|
||||
it('correctly matches bash command wildcards', () => {
|
||||
const starRegex = wildcardToRegex('*')
|
||||
expect(starRegex.test('npm install')).toBe(true)
|
||||
expect(starRegex.test('git commit -m "test"')).toBe(true)
|
||||
|
||||
const npmRegex = wildcardToRegex('npm *')
|
||||
expect(npmRegex.test('npm install')).toBe(true)
|
||||
expect(npmRegex.test('npm test')).toBe(true)
|
||||
expect(npmRegex.test('git push')).toBe(false)
|
||||
|
||||
const exactRegex = wildcardToRegex('rm -rf .pi')
|
||||
expect(exactRegex.test('rm -rf .pi')).toBe(true)
|
||||
expect(exactRegex.test('rm -rf /')).toBe(false)
|
||||
})
|
||||
|
||||
it('correctly matches agent tool name wildcards', () => {
|
||||
const starTool = wildcardToRegex('*')
|
||||
expect(starTool.test('analyze_image')).toBe(true)
|
||||
expect(starTool.test('screenshot')).toBe(true)
|
||||
|
||||
const exactTool = wildcardToRegex('analyze_image')
|
||||
expect(exactTool.test('analyze_image')).toBe(true)
|
||||
expect(exactTool.test('screenshot')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('QuotaService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('creates, reads, updates, and deletes quota rules', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Quota Team' },
|
||||
})
|
||||
|
||||
// Create rule
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 100000,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
expect(rule.id).toBeDefined()
|
||||
expect(rule.teamId).toBe(team.id)
|
||||
expect(rule.scopeMode).toBe('all_members')
|
||||
expect(rule.limit).toBe(100000)
|
||||
expect(rule.period).toBe('1hour')
|
||||
|
||||
// Get rule
|
||||
const fetched = await quotaService.getRule(team.id, rule.id)
|
||||
expect(fetched.id).toBe(rule.id)
|
||||
expect(fetched.limit).toBe(100000)
|
||||
|
||||
// List rules
|
||||
const list = await quotaService.listRules(team.id)
|
||||
expect(list.total).toBe(1)
|
||||
expect(list.rules[0].id).toBe(rule.id)
|
||||
|
||||
// Update rule
|
||||
const updated = await quotaService.updateRule(team.id, rule.id, {
|
||||
limit: 200000,
|
||||
enabled: false,
|
||||
})
|
||||
expect(updated.limit).toBe(200000)
|
||||
expect(updated.enabled).toBe(false)
|
||||
|
||||
// Delete rule
|
||||
await quotaService.deleteRule(team.id, rule.id)
|
||||
const afterDelete = await quotaService.listRules(team.id)
|
||||
expect(afterDelete.total).toBe(0)
|
||||
})
|
||||
|
||||
it('validates selected members on rule creation', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Quota Team' },
|
||||
})
|
||||
|
||||
// Missing user should throw 400
|
||||
await expect(
|
||||
quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: ['non-existent-user-id'],
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1day',
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('uses the latest database rule state for every quota check', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Fresh Quota Rule Team' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
const event = {
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost' as const,
|
||||
}
|
||||
|
||||
expect((await quotaService.checkQuota(event)).matchedRules).toHaveLength(1)
|
||||
|
||||
await prisma.quotaRule.update({
|
||||
where: { id: rule.id },
|
||||
data: { enabled: false },
|
||||
})
|
||||
|
||||
expect((await quotaService.checkQuota(event)).matchedRules).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('enforces check and consumes quota for all_members (shared pool)', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Shared Quota Team' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Check with 0 before consumption
|
||||
const checkResult = await quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
0,
|
||||
)
|
||||
expect(checkResult.allowed).toBe(true)
|
||||
|
||||
// Consume 600 tokens
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
600,
|
||||
)
|
||||
|
||||
// Check with 300 tokens (600 + 300 = 900 <= 1000) -> allowed
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
300,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
|
||||
// Check with 500 tokens (600 + 500 = 1100 > 1000) -> throws QuotaExceededError
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
500,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Consume another 400 tokens -> exactly 1000 consumed
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
400,
|
||||
)
|
||||
|
||||
// Now even checkQuota with 1 token should fail
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
})
|
||||
|
||||
it('enforces each_member scope independently for each member', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Each Member Team' },
|
||||
})
|
||||
|
||||
const userAlice = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
const userBob = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
// Create rule: each member with role editor gets 5 skill calls per 1hour
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
role: 'editor',
|
||||
resource: 'agent_skill_call_count',
|
||||
resourceData: { id: 'skill_1' },
|
||||
limit: 5,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Alice consumes 5 skill calls
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userAlice.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_skill_call_count',
|
||||
resourceData: { id: 'skill_1' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
// Alice should be blocked on 6th call
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userAlice.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_skill_call_count',
|
||||
resourceData: { id: 'skill_1' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Bob (also an editor) should NOT be blocked (independent tracking)
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userBob.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_skill_call_count',
|
||||
resourceData: { id: 'skill_1' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
|
||||
// Reviewer should not match editor rule
|
||||
const reviewerCheck = await quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userBob.id,
|
||||
role: 'reviewer',
|
||||
resource: 'agent_skill_call_count',
|
||||
resourceData: { id: 'skill_1' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
expect(reviewerCheck.matchedRules).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('enforces selected_members scope correctly', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Selected Members Team' },
|
||||
})
|
||||
|
||||
const userSelected = await prisma.user.create({
|
||||
data: { name: 'Selected User', email: 'sel@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userSelected.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const userOther = await prisma.user.create({
|
||||
data: { name: 'Other User', email: 'other@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userOther.id, role: 'editor' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [userSelected.id],
|
||||
resource: 'agent_cost',
|
||||
limit: 5,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Selected user consumes 5
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userSelected.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
5,
|
||||
)
|
||||
|
||||
// Selected user is blocked
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userSelected.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Other user does not match the rule -> allowed
|
||||
const otherCheck = await quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userOther.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
10,
|
||||
)
|
||||
expect(otherCheck.matchedRules).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('matches bash command wildcard rules', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Bash Quota Team' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { match: 'npm *' },
|
||||
limit: 2,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// npm test matches -> consume 1
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'npm test' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
// npm install matches -> consume 1 (total = 2)
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'npm install' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
// 3rd npm command should be blocked
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'npm run build' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// git command does not match 'npm *' -> allowed
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'git status' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
})
|
||||
|
||||
it('matches agent tool call rules and wildcards', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Tool Quota Team' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'analyze_image' },
|
||||
limit: 1,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// First call to analyze_image
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'analyze_image' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
// 2nd call to analyze_image is blocked
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'analyze_image' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Call to create_file does not match -> allowed
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'create_file' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
})
|
||||
|
||||
it('handles period window rollover and resets usage in-place with no history tables', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Window Rollover Team' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Simulate an expired period by creating a past QuotaRecord
|
||||
const pastStart = new Date(Date.now() - 2 * 60 * 60 * 1000)
|
||||
const pastEnd = new Date(Date.now() - 1 * 60 * 60 * 1000)
|
||||
|
||||
await prisma.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: rule.id,
|
||||
teamId: team.id,
|
||||
userId: null,
|
||||
periodStart: pastStart,
|
||||
periodEnd: pastEnd,
|
||||
consumed: 10, // fully consumed in past window
|
||||
},
|
||||
})
|
||||
|
||||
// Current check should be ALLOWED because the old window expired
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
5,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
|
||||
// Consuming now resets the single record in-place
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
5,
|
||||
)
|
||||
|
||||
const records = await prisma.quotaRecord.findMany({
|
||||
where: { ruleId: rule.id },
|
||||
})
|
||||
|
||||
// No extra history records (exactly 1 record row updated in place)
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(5)
|
||||
})
|
||||
|
||||
it('lists rule records accurately with lazy reset status', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Records List Team' },
|
||||
})
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Alice Member', email: 'alice.member@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 50000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Before any usage: listRuleRecords returns member with consumed: 0, isWindowActive: false
|
||||
const initialRecords = await quotaService.listRuleRecords(team.id, rule.id)
|
||||
expect(initialRecords.total).toBe(1)
|
||||
expect(initialRecords.records[0].userId).toBe(user.id)
|
||||
expect(initialRecords.records[0].consumed).toBe(0)
|
||||
expect(initialRecords.records[0].remaining).toBe(50000)
|
||||
expect(initialRecords.records[0].isWindowActive).toBe(false)
|
||||
|
||||
// Consume 10000 tokens
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
10000,
|
||||
)
|
||||
|
||||
// After usage: active window with consumed = 10000
|
||||
const activeRecords = await quotaService.listRuleRecords(team.id, rule.id)
|
||||
expect(activeRecords.records[0].consumed).toBe(10000)
|
||||
expect(activeRecords.records[0].remaining).toBe(40000)
|
||||
expect(activeRecords.records[0].isWindowActive).toBe(true)
|
||||
})
|
||||
|
||||
it('enforces multiple matching rules simultaneously', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Multi Rule Team' },
|
||||
})
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Charlie', email: 'charlie@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Rule 1: Team overall token limit 10,000 (all_members)
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Rule 2: User specific token limit 2,000 (selected_members)
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [user.id],
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 2000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Consuming 2000 tokens for Charlie
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
2000,
|
||||
)
|
||||
|
||||
// Charlie is blocked by user rule (2000 limit reached)
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
100,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Another user in the same team is NOT blocked by Charlie's limit, only by team limit
|
||||
const userDave = await prisma.user.create({
|
||||
data: { name: 'Dave', email: 'dave@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userDave.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
1000,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
})
|
||||
|
||||
it('rejects selected_members if user is not a member of the team on create', async () => {
|
||||
const team1 = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const team2 = await prisma.team.create({ data: { name: 'Team 2' } })
|
||||
|
||||
const userInTeam1 = await prisma.user.create({
|
||||
data: { name: 'Member 1', email: 'm1@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team1.id, userId: userInTeam1.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const userInTeam2 = await prisma.user.create({
|
||||
data: { name: 'Member 2', email: 'm2@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team2.id, userId: userInTeam2.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Creating rule on Team 1 with user from Team 2 should throw 400
|
||||
await expect(
|
||||
quotaService.createRule(team1.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [userInTeam2.id],
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1day',
|
||||
}),
|
||||
).rejects.toThrow('One or more selected users are not members of the team')
|
||||
})
|
||||
|
||||
it('validates merged rule and rejects invalid partial updates', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Validation Team' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'User 1', email: 'u1@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
// Updating resource to agent_skill_call_count without resourceData.id should fail validation
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, rule.id, {
|
||||
resource: 'agent_skill_call_count',
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
// Updating scopeMode to selected_members without userIds should fail validation
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, rule.id, {
|
||||
scopeMode: 'selected_members',
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
// Updating userIds with a user from outside the team should fail validation
|
||||
const otherUser = await prisma.user.create({
|
||||
data: { name: 'Other User', email: 'other_team@example.com', password: 'pw' },
|
||||
})
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, rule.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [otherUser.id],
|
||||
}),
|
||||
).rejects.toThrow('One or more selected users are not members of the team')
|
||||
})
|
||||
|
||||
it('resets existing quota records when accounting dimensions change', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Reset Records Team' } })
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
// Consume 500 tokens
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
500,
|
||||
)
|
||||
|
||||
let records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(500)
|
||||
|
||||
// Update resource to agent_cost (limit 10)
|
||||
await quotaService.updateRule(team.id, rule.id, {
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
})
|
||||
|
||||
// Records should be reset
|
||||
records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(0)
|
||||
|
||||
// Consume $2 under the new resource
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
2,
|
||||
)
|
||||
|
||||
records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(2)
|
||||
})
|
||||
|
||||
it('handles concurrent first consumption for all_members without creating duplicate records', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Concurrent Quota Team' } })
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
// Concurrently trigger 5 quota consumption calls for the first time
|
||||
await Promise.all([
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 10),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 20),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 30),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 40),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 50),
|
||||
])
|
||||
|
||||
const records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(150)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,747 @@
|
||||
import {
|
||||
prisma,
|
||||
Prisma,
|
||||
type QuotaPeriod,
|
||||
type QuotaRecord,
|
||||
type QuotaResourceType,
|
||||
type QuotaRule,
|
||||
type TeamMemberRole,
|
||||
} from '@shumai/db'
|
||||
import {
|
||||
type CreateQuotaRuleRequest,
|
||||
type ListQuotaRulesResponse,
|
||||
type QuotaRuleResponse,
|
||||
type ListQuotaRecordsResponse,
|
||||
type QuotaRecordResponse,
|
||||
type UpdateQuotaRuleRequest,
|
||||
normalizeQuotaPeriod,
|
||||
formatQuotaPeriod,
|
||||
skillResourceDataSchema,
|
||||
mcpResourceDataSchema,
|
||||
bashResourceDataSchema,
|
||||
toolResourceDataSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
export class QuotaExceededError extends Error {
|
||||
public readonly policyId: string
|
||||
public readonly resource: string
|
||||
public readonly limit: number
|
||||
public readonly consumed: number
|
||||
public readonly periodEnd: Date
|
||||
|
||||
constructor(params: {
|
||||
policyId: string
|
||||
resource: string
|
||||
limit: number
|
||||
consumed: number
|
||||
periodEnd: Date
|
||||
message?: string
|
||||
}) {
|
||||
const msg =
|
||||
params.message ||
|
||||
`Quota exceeded for ${params.resource}: limit of ${params.limit} reached (currently consumed: ${params.consumed}). Resets at ${params.periodEnd.toISOString()}.`
|
||||
super(msg)
|
||||
this.name = 'QuotaExceededError'
|
||||
this.policyId = params.policyId
|
||||
this.resource = params.resource
|
||||
this.limit = params.limit
|
||||
this.consumed = params.consumed
|
||||
this.periodEnd = params.periodEnd
|
||||
}
|
||||
}
|
||||
|
||||
export interface QuotaEventResourceData {
|
||||
skillId?: string
|
||||
mcpServerId?: string
|
||||
command?: string
|
||||
name?: string
|
||||
toolName?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface QuotaEvent {
|
||||
teamId: string
|
||||
userId?: string | null
|
||||
role?: TeamMemberRole | null
|
||||
resource: QuotaResourceType
|
||||
resourceData?: QuotaEventResourceData
|
||||
}
|
||||
|
||||
export function periodToDurationMs(period: QuotaPeriod | string): number {
|
||||
switch (period) {
|
||||
case 'one_hour':
|
||||
case '1hour':
|
||||
return 60 * 60 * 1000
|
||||
case 'five_hours':
|
||||
case '5hour':
|
||||
return 5 * 60 * 60 * 1000
|
||||
case 'one_day':
|
||||
case '1day':
|
||||
return 24 * 60 * 60 * 1000
|
||||
case 'seven_days':
|
||||
case '7day':
|
||||
return 7 * 24 * 60 * 60 * 1000
|
||||
default:
|
||||
return 60 * 60 * 1000
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a wildcard pattern (with * and ?) into a regular expression.
|
||||
*/
|
||||
export function wildcardToRegex(pattern: string): RegExp {
|
||||
const trimmed = pattern.trim()
|
||||
if (trimmed === '*' || trimmed === '') {
|
||||
return /^.*$/s
|
||||
}
|
||||
// Escape regex special chars except * and ?
|
||||
const escaped = trimmed.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
const regexStr = '^' + escaped.replace(/\*/g, '.*').replace(/\?/g, '.') + '$'
|
||||
return new RegExp(regexStr, 's')
|
||||
}
|
||||
|
||||
function matchesQuotaRule(rule: QuotaRule, event: QuotaEvent): boolean {
|
||||
if (!rule.enabled) return false
|
||||
if (event.teamId !== rule.teamId) return false
|
||||
if (event.resource !== rule.resource) return false
|
||||
|
||||
// Scope check
|
||||
if (rule.scopeMode === 'all_members') {
|
||||
if (rule.role && event.role !== rule.role) return false
|
||||
} else if (rule.scopeMode === 'each_member') {
|
||||
if (!event.userId) return false
|
||||
if (rule.role && event.role !== rule.role) return false
|
||||
} else if (rule.scopeMode === 'selected_members') {
|
||||
if (!event.userId) return false
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : null
|
||||
if (!userIds || !userIds.includes(event.userId)) return false
|
||||
}
|
||||
|
||||
const resourceData = (rule.resourceData as Record<string, unknown> | null) ?? null
|
||||
|
||||
// Resource data check
|
||||
if (rule.resource === 'agent_skill_call_count') {
|
||||
const targetId = resourceData?.id ?? resourceData?.skillId
|
||||
const eventSkillId = event.resourceData?.skillId ?? event.resourceData?.id
|
||||
if (targetId && eventSkillId !== targetId) return false
|
||||
} else if (rule.resource === 'agent_mcp_call_count') {
|
||||
const targetId = resourceData?.id ?? resourceData?.mcpServerId
|
||||
const eventMcpId = event.resourceData?.mcpServerId ?? event.resourceData?.id
|
||||
if (targetId && eventMcpId !== targetId) return false
|
||||
} else if (rule.resource === 'agent_bash_call_count' && resourceData?.match) {
|
||||
const bashMatcher = wildcardToRegex(String(resourceData.match))
|
||||
const command = event.resourceData?.command ?? ''
|
||||
if (!bashMatcher.test(command)) return false
|
||||
} else if (
|
||||
rule.resource === 'agent_tool_call_count' &&
|
||||
(resourceData?.name || resourceData?.toolName)
|
||||
) {
|
||||
const toolMatcher = wildcardToRegex(String(resourceData.name ?? resourceData.toolName))
|
||||
const toolName = String(event.resourceData?.name ?? event.resourceData?.toolName ?? '')
|
||||
if (!toolMatcher.test(toolName)) return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function getQuotaRuleTargetUserId(rule: QuotaRule, event: QuotaEvent): string | null {
|
||||
if (rule.scopeMode === 'all_members') {
|
||||
return null
|
||||
}
|
||||
return event.userId ?? null
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
interface RawQuotaRecord {
|
||||
id: string
|
||||
rule_id: string
|
||||
team_id: string
|
||||
user_id: string | null
|
||||
period_start: Date | null
|
||||
period_end: Date | null
|
||||
consumed: number
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
export class QuotaService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private mapRuleToResponse(rule: QuotaRule, recordsCount?: number): QuotaRuleResponse {
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : undefined
|
||||
|
||||
return {
|
||||
id: rule.id,
|
||||
teamId: rule.teamId,
|
||||
scopeMode: rule.scopeMode,
|
||||
role: rule.role ?? undefined,
|
||||
userIds,
|
||||
resource: rule.resource,
|
||||
resourceData: (rule.resourceData as Record<string, unknown> | null) ?? undefined,
|
||||
limit: rule.limit,
|
||||
period: formatQuotaPeriod(rule.period) as QuotaRuleResponse['period'],
|
||||
enabled: rule.enabled,
|
||||
recordsCount,
|
||||
createdAt: rule.createdAt.toISOString(),
|
||||
updatedAt: rule.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
async createRule(teamId: string, req: CreateQuotaRuleRequest): Promise<QuotaRuleResponse> {
|
||||
if (req.scopeMode === 'selected_members') {
|
||||
if (!req.userIds || req.userIds.length === 0) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'userIds must contain at least one user when scopeMode is "selected_members"',
|
||||
})
|
||||
}
|
||||
const members = await this.prismaClient.teamMember.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
userId: { in: req.userIds },
|
||||
},
|
||||
select: { userId: true },
|
||||
})
|
||||
if (members.length !== req.userIds.length) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'One or more selected users are not members of the team',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const rule = await this.prismaClient.quotaRule.create({
|
||||
data: {
|
||||
teamId,
|
||||
scopeMode: req.scopeMode,
|
||||
role: req.scopeMode !== 'selected_members' ? (req.role ?? null) : null,
|
||||
userIds:
|
||||
req.scopeMode === 'selected_members' && req.userIds ? req.userIds : Prisma.JsonNull,
|
||||
resource: req.resource,
|
||||
resourceData: req.resourceData ?? Prisma.JsonNull,
|
||||
limit: req.limit,
|
||||
period: normalizeQuotaPeriod(req.period),
|
||||
enabled: req.enabled ?? true,
|
||||
},
|
||||
})
|
||||
|
||||
return this.mapRuleToResponse(rule, 0)
|
||||
}
|
||||
|
||||
async updateRule(
|
||||
teamId: string,
|
||||
ruleId: string,
|
||||
req: UpdateQuotaRuleRequest,
|
||||
): Promise<QuotaRuleResponse> {
|
||||
const existing = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!existing || existing.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
const effectiveScopeMode = req.scopeMode ?? existing.scopeMode
|
||||
const effectiveRole =
|
||||
effectiveScopeMode === 'selected_members'
|
||||
? null
|
||||
: req.role !== undefined
|
||||
? req.role
|
||||
: existing.role
|
||||
const effectiveUserIds =
|
||||
effectiveScopeMode === 'selected_members'
|
||||
? req.userIds !== undefined
|
||||
? req.userIds
|
||||
: Array.isArray(existing.userIds)
|
||||
? (existing.userIds as string[])
|
||||
: []
|
||||
: null
|
||||
const effectiveResource = req.resource ?? existing.resource
|
||||
const effectiveResourceData =
|
||||
req.resourceData !== undefined
|
||||
? req.resourceData
|
||||
: (existing.resourceData as Record<string, unknown> | null)
|
||||
const effectiveLimit = req.limit ?? existing.limit
|
||||
const effectivePeriod = req.period ? normalizeQuotaPeriod(req.period) : existing.period
|
||||
const effectiveEnabled = req.enabled ?? existing.enabled
|
||||
|
||||
// Validate effective merged state
|
||||
if (effectiveScopeMode === 'selected_members') {
|
||||
if (!effectiveUserIds || effectiveUserIds.length === 0) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'userIds must contain at least one user when scopeMode is "selected_members"',
|
||||
})
|
||||
}
|
||||
const members = await this.prismaClient.teamMember.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
userId: { in: effectiveUserIds },
|
||||
},
|
||||
select: { userId: true },
|
||||
})
|
||||
if (members.length !== effectiveUserIds.length) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'One or more selected users are not members of the team',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveResource === 'agent_skill_call_count') {
|
||||
const res = skillResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.id is required for agent_skill_call_count',
|
||||
})
|
||||
}
|
||||
} else if (effectiveResource === 'agent_mcp_call_count') {
|
||||
const res = mcpResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.id is required for agent_mcp_call_count',
|
||||
})
|
||||
}
|
||||
} else if (effectiveResource === 'agent_bash_call_count') {
|
||||
const res = bashResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.match is required for agent_bash_call_count',
|
||||
})
|
||||
}
|
||||
} else if (effectiveResource === 'agent_tool_call_count') {
|
||||
const res = toolResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.name is required for agent_tool_call_count',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveLimit <= 0) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Limit must be greater than 0',
|
||||
})
|
||||
}
|
||||
|
||||
const isAccountingDimensionChanged =
|
||||
(req.resource !== undefined && req.resource !== existing.resource) ||
|
||||
(req.period !== undefined && normalizeQuotaPeriod(req.period) !== existing.period) ||
|
||||
(req.scopeMode !== undefined && req.scopeMode !== existing.scopeMode) ||
|
||||
(req.role !== undefined && req.role !== existing.role) ||
|
||||
(req.resourceData !== undefined &&
|
||||
JSON.stringify(req.resourceData) !== JSON.stringify(existing.resourceData))
|
||||
|
||||
const updated = await this.prismaClient.$transaction(async (tx) => {
|
||||
if (isAccountingDimensionChanged) {
|
||||
// Reset all records when accounting dimensions change
|
||||
await tx.quotaRecord.deleteMany({
|
||||
where: { ruleId },
|
||||
})
|
||||
} else if (effectiveScopeMode === 'selected_members' && req.userIds !== undefined) {
|
||||
// Clean up records for removed users if updating userIds
|
||||
if (req.userIds && req.userIds.length > 0) {
|
||||
await tx.quotaRecord.deleteMany({
|
||||
where: {
|
||||
ruleId,
|
||||
userId: { notIn: req.userIds },
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const data: Prisma.QuotaRuleUpdateInput = {
|
||||
scopeMode: effectiveScopeMode,
|
||||
role: effectiveRole,
|
||||
userIds:
|
||||
effectiveScopeMode === 'selected_members' && effectiveUserIds
|
||||
? effectiveUserIds
|
||||
: Prisma.JsonNull,
|
||||
resource: effectiveResource,
|
||||
resourceData: effectiveResourceData ?? Prisma.JsonNull,
|
||||
limit: effectiveLimit,
|
||||
period: effectivePeriod,
|
||||
enabled: effectiveEnabled,
|
||||
}
|
||||
|
||||
return tx.quotaRule.update({
|
||||
where: { id: ruleId },
|
||||
data,
|
||||
})
|
||||
})
|
||||
|
||||
const recordsCount = await this.prismaClient.quotaRecord.count({
|
||||
where: { ruleId },
|
||||
})
|
||||
|
||||
return this.mapRuleToResponse(updated, recordsCount)
|
||||
}
|
||||
|
||||
async deleteRule(teamId: string, ruleId: string): Promise<void> {
|
||||
const existing = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!existing || existing.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
await this.prismaClient.quotaRule.delete({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
}
|
||||
|
||||
async getRule(teamId: string, ruleId: string): Promise<QuotaRuleResponse> {
|
||||
const rule = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!rule || rule.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
const recordsCount = await this.prismaClient.quotaRecord.count({
|
||||
where: { ruleId },
|
||||
})
|
||||
|
||||
return this.mapRuleToResponse(rule, recordsCount)
|
||||
}
|
||||
|
||||
async listRules(teamId: string): Promise<ListQuotaRulesResponse> {
|
||||
const rules = await this.prismaClient.quotaRule.findMany({
|
||||
where: { teamId },
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
|
||||
const ruleResponses = await Promise.all(
|
||||
rules.map(async (rule) => {
|
||||
const recordsCount = await this.prismaClient.quotaRecord.count({
|
||||
where: { ruleId: rule.id },
|
||||
})
|
||||
return this.mapRuleToResponse(rule, recordsCount)
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
rules: ruleResponses,
|
||||
total: ruleResponses.length,
|
||||
}
|
||||
}
|
||||
|
||||
async listRuleRecords(teamId: string, ruleId: string): Promise<ListQuotaRecordsResponse> {
|
||||
const rule = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!rule || rule.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
if (rule.scopeMode === 'all_members') {
|
||||
const record = await this.prismaClient.quotaRecord.findFirst({
|
||||
where: { ruleId: rule.id, userId: null },
|
||||
})
|
||||
|
||||
const isWindowActive = Boolean(
|
||||
record?.periodStart &&
|
||||
record?.periodEnd &&
|
||||
now >= record.periodStart &&
|
||||
now < record.periodEnd,
|
||||
)
|
||||
|
||||
const consumed = isWindowActive ? (record?.consumed ?? 0) : 0
|
||||
const remaining = Math.max(0, rule.limit - consumed)
|
||||
const percent =
|
||||
rule.limit > 0 ? Math.min(100, Number(((consumed / rule.limit) * 100).toFixed(2))) : 0
|
||||
|
||||
const res: QuotaRecordResponse = {
|
||||
id: record?.id ?? null,
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId: null,
|
||||
user: null,
|
||||
periodStart:
|
||||
isWindowActive && record?.periodStart ? record.periodStart.toISOString() : null,
|
||||
periodEnd: isWindowActive && record?.periodEnd ? record.periodEnd.toISOString() : null,
|
||||
consumed,
|
||||
remaining,
|
||||
percent,
|
||||
isWindowActive,
|
||||
}
|
||||
|
||||
return {
|
||||
records: [res],
|
||||
total: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// For each_member or selected_members
|
||||
type MemberTarget = { id: string; name: string; email: string; image?: string | null }
|
||||
let targetUsers: MemberTarget[] = []
|
||||
|
||||
if (rule.scopeMode === 'selected_members') {
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : []
|
||||
if (userIds.length > 0) {
|
||||
targetUsers = await this.prismaClient.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// each_member
|
||||
const memberWhere: Prisma.TeamMemberWhereInput = { teamId }
|
||||
if (rule.role) {
|
||||
memberWhere.role = rule.role
|
||||
}
|
||||
const members = await this.prismaClient.teamMember.findMany({
|
||||
where: memberWhere,
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
targetUsers = members.map((m) => m.user)
|
||||
}
|
||||
|
||||
const existingRecords = await this.prismaClient.quotaRecord.findMany({
|
||||
where: {
|
||||
ruleId: rule.id,
|
||||
userId: { in: targetUsers.map((u) => u.id) },
|
||||
},
|
||||
})
|
||||
|
||||
const recordByUserId = new Map<string, QuotaRecord>()
|
||||
for (const r of existingRecords) {
|
||||
if (r.userId) recordByUserId.set(r.userId, r)
|
||||
}
|
||||
|
||||
const records: QuotaRecordResponse[] = targetUsers.map((user) => {
|
||||
const record = recordByUserId.get(user.id)
|
||||
const isWindowActive = Boolean(
|
||||
record?.periodStart &&
|
||||
record?.periodEnd &&
|
||||
now >= record.periodStart &&
|
||||
now < record.periodEnd,
|
||||
)
|
||||
|
||||
const consumed = isWindowActive ? (record?.consumed ?? 0) : 0
|
||||
const remaining = Math.max(0, rule.limit - consumed)
|
||||
const percent =
|
||||
rule.limit > 0 ? Math.min(100, Number(((consumed / rule.limit) * 100).toFixed(2))) : 0
|
||||
|
||||
return {
|
||||
id: record?.id ?? null,
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId: user.id,
|
||||
user: {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
image: user.image ?? null,
|
||||
},
|
||||
periodStart:
|
||||
isWindowActive && record?.periodStart ? record.periodStart.toISOString() : null,
|
||||
periodEnd: isWindowActive && record?.periodEnd ? record.periodEnd.toISOString() : null,
|
||||
consumed,
|
||||
remaining,
|
||||
percent,
|
||||
isWindowActive,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
records,
|
||||
total: records.length,
|
||||
}
|
||||
}
|
||||
|
||||
private async findMatchingRules(event: QuotaEvent): Promise<QuotaRule[]> {
|
||||
const rules = await this.prismaClient.quotaRule.findMany({
|
||||
where: {
|
||||
teamId: event.teamId,
|
||||
resource: event.resource,
|
||||
enabled: true,
|
||||
},
|
||||
})
|
||||
|
||||
return rules.filter((rule) => matchesQuotaRule(rule, event))
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates whether an action is permitted under all active matching quota rules.
|
||||
* Performs an atomic pre-check with SELECT ... FOR UPDATE.
|
||||
* Throws QuotaExceededError if any matching rule is exceeded.
|
||||
*/
|
||||
async checkQuota(
|
||||
event: QuotaEvent,
|
||||
amount: number = 0,
|
||||
): Promise<{ allowed: boolean; matchedRules: QuotaRule[] }> {
|
||||
const rules = await this.findMatchingRules(event)
|
||||
if (rules.length === 0) {
|
||||
return { allowed: true, matchedRules: [] }
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
for (const rule of rules) {
|
||||
const targetUserId = getQuotaRuleTargetUserId(rule, event)
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
if (targetUserId === null) {
|
||||
// Serialize all_members record checks/creations on the parent rule row
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
}
|
||||
|
||||
let rawRecord = targetUserId
|
||||
? ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
: ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
|
||||
if (!rawRecord && targetUserId !== null) {
|
||||
// Lock parent rule on first user record check and re-query
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
rawRecord =
|
||||
(
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null
|
||||
}
|
||||
|
||||
const isWindowActive = Boolean(
|
||||
rawRecord?.period_start &&
|
||||
rawRecord?.period_end &&
|
||||
now >= rawRecord.period_start &&
|
||||
now < rawRecord.period_end,
|
||||
)
|
||||
|
||||
const consumed = isWindowActive ? (rawRecord?.consumed ?? 0) : 0
|
||||
const periodEnd = isWindowActive
|
||||
? rawRecord!.period_end!
|
||||
: new Date(now.getTime() + periodToDurationMs(rule.period))
|
||||
|
||||
if (consumed + amount > rule.limit) {
|
||||
throw new QuotaExceededError({
|
||||
policyId: rule.id,
|
||||
resource: rule.resource,
|
||||
limit: rule.limit,
|
||||
consumed,
|
||||
periodEnd,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return { allowed: true, matchedRules: rules }
|
||||
}
|
||||
|
||||
/**
|
||||
* Records consumed usage across all matching quota rules.
|
||||
* Lazy resets the period window in-place when previous window has expired.
|
||||
* Uses SELECT ... FOR UPDATE inside transactions for atomic concurrency protection.
|
||||
*/
|
||||
async consumeQuota(event: QuotaEvent, amount: number): Promise<void> {
|
||||
if (amount <= 0) return
|
||||
|
||||
const rules = await this.findMatchingRules(event)
|
||||
if (rules.length === 0) return
|
||||
|
||||
const now = new Date()
|
||||
|
||||
for (const rule of rules) {
|
||||
const targetUserId = getQuotaRuleTargetUserId(rule, event)
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
if (targetUserId === null) {
|
||||
// Serialize all_members (shared pool) creations and updates on the parent rule row
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
}
|
||||
|
||||
let rawRecord = targetUserId
|
||||
? ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
: ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
|
||||
if (!rawRecord && targetUserId !== null) {
|
||||
// Lock parent rule on first user record creation and re-query
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
rawRecord =
|
||||
(
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null
|
||||
}
|
||||
|
||||
const isWindowActive = Boolean(
|
||||
rawRecord?.period_start &&
|
||||
rawRecord?.period_end &&
|
||||
now >= rawRecord.period_start &&
|
||||
now < rawRecord.period_end,
|
||||
)
|
||||
|
||||
if (isWindowActive && rawRecord) {
|
||||
await tx.quotaRecord.update({
|
||||
where: { id: rawRecord.id },
|
||||
data: {
|
||||
consumed: { increment: amount },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const periodStart = now
|
||||
const periodEnd = new Date(now.getTime() + periodToDurationMs(rule.period))
|
||||
|
||||
if (rawRecord) {
|
||||
await tx.quotaRecord.update({
|
||||
where: { id: rawRecord.id },
|
||||
data: {
|
||||
periodStart,
|
||||
periodEnd,
|
||||
consumed: amount,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await tx.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId: targetUserId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
consumed: amount,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const quotaService = new QuotaService()
|
||||
Reference in New Issue
Block a user