File size: 14,590 Bytes
22087d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
from typing import Dict, Any, Optional
from datetime import datetime, timezone, timedelta
from core.utils.logger import logger
from core.utils.config import config
from core.utils.cache import Cache
from core.utils import limits_repo


def _get_free_tier_defaults() -> Dict[str, Any]:
    try:
        from core.billing.shared.config import TIERS
        free_tier = TIERS.get('free')
        if free_tier:
            return {
                'name': 'free',
                'concurrent_runs': free_tier.concurrent_runs,
                'thread_limit': free_tier.thread_limit,
                'project_limit': free_tier.project_limit,
                'custom_workers_limit': free_tier.custom_workers_limit,
                'scheduled_triggers_limit': free_tier.scheduled_triggers_limit,
                'app_triggers_limit': free_tier.app_triggers_limit,
            }
    except Exception:
        pass

    return {
        'name': 'free',
        'concurrent_runs': 1,
        'thread_limit': 10,
        'project_limit': 20,
        'custom_workers_limit': 0,
        'scheduled_triggers_limit': 0,
        'app_triggers_limit': 0,
    }


async def _get_tier_info_if_needed(account_id: str, tier_info: Optional[Dict] = None) -> Dict:
    if tier_info is not None:
        return tier_info
    
    try:
        from core.agents.pipeline.slot_manager import get_tier_limits
        limits = await get_tier_limits(account_id)
        defaults = _get_free_tier_defaults()
        return {
            'name': limits.get('name', 'free'),
            'concurrent_runs': limits.get('concurrent_runs', defaults['concurrent_runs']),
            'thread_limit': limits.get('thread_limit', defaults['thread_limit']),
            'project_limit': limits.get('project_limit', defaults['project_limit']),
            'custom_workers_limit': limits.get('custom_workers_limit', defaults['custom_workers_limit']),
            'scheduled_triggers_limit': limits.get('scheduled_triggers_limit', defaults['scheduled_triggers_limit']),
            'app_triggers_limit': limits.get('app_triggers_limit', defaults['app_triggers_limit']),
        }
    except Exception as e:
        logger.warning(f"Could not get tier for {account_id}: {e}, using defaults")
        return _get_free_tier_defaults()


async def check_agent_run_limit(account_id: str, tier_info: Optional[Dict] = None, client=None) -> Dict[str, Any]:
    try:
        from core.agents.pipeline.slot_manager import get_count, get_tier_limits
        
        tier = await get_tier_limits(account_id)
        concurrent_runs_limit = tier.get('concurrent_runs', 1)
        tier_name = tier.get('name', 'free')
        
        running_count = await get_count(account_id)
        
        return {
            'can_start': running_count < concurrent_runs_limit,
            'running_count': running_count,
            'running_thread_ids': [],
            'limit': concurrent_runs_limit,
            'tier_name': tier_name
        }

    except Exception as e:
        logger.error(f"Error checking agent run limit for {account_id}: {e}")
        return {
            'can_start': True,
            'running_count': 0,
            'running_thread_ids': [],
            'limit': 1,
            'tier_name': 'free'
        }


async def check_agent_count_limit(account_id: str, tier_info: Optional[Dict] = None, client=None) -> Dict[str, Any]:
    try:
        if config.ENV_MODE.value == "local":
            return {
                'can_create': True,
                'current_count': 0,
                'limit': 999999,
                'tier_name': 'local'
            }
        
        tier = await _get_tier_info_if_needed(account_id, tier_info)
        tier_name = tier.get('name', 'free')
        agent_limit = tier.get('custom_workers_limit', 1)
        
        current_count = await limits_repo.count_user_agents(account_id)
        can_create = current_count < agent_limit
        
        logger.debug(f"Account {account_id} has {current_count}/{agent_limit} agents (tier: {tier_name})")
        
        return {
            'can_create': can_create,
            'current_count': current_count,
            'limit': agent_limit,
            'tier_name': tier_name
        }
        
    except Exception as e:
        logger.error(f"Error checking agent count limit for {account_id}: {e}")
        return {
            'can_create': True,
            'current_count': 0,
            'limit': 1,
            'tier_name': 'free'
        }


async def check_project_count_limit(account_id: str, tier_info: Optional[Dict] = None, client=None) -> Dict[str, Any]:
    try:
        from core.agents.pipeline.slot_manager import check_project_limit as sm_check_project_limit
        
        result = await sm_check_project_limit(account_id)
        tier = await _get_tier_info_if_needed(account_id, tier_info)
        
        return {
            'can_create': result.allowed,
            'current_count': result.current_count,
            'limit': result.limit,
            'tier_name': tier.get('name', 'free')
        }
        
    except Exception as e:
        logger.error(f"Error checking project count limit for {account_id}: {e}")
        return {
            'can_create': True,
            'current_count': 0,
            'limit': 2,
            'tier_name': 'free'
        }


async def check_trigger_limit(
    account_id: str, 
    agent_id: str = None, 
    trigger_type: str = None, 
    tier_info: Optional[Dict] = None,
    client=None
) -> Dict[str, Any]:
    try:
        tier = await _get_tier_info_if_needed(account_id, tier_info)
        tier_name = tier.get('name', 'free')
        scheduled_limit = tier.get('scheduled_triggers_limit', 1)
        app_limit = tier.get('app_triggers_limit', 2)
        
        if agent_id is None or trigger_type is None:
            trigger_counts = await limits_repo.count_all_triggers_for_account(account_id)
            scheduled_count = trigger_counts.get("scheduled", 0)
            app_count = trigger_counts.get("app", 0)
            
            return {
                'scheduled': {
                    'current_count': scheduled_count,
                    'limit': scheduled_limit,
                    'can_create': scheduled_count < scheduled_limit
                },
                'app': {
                    'current_count': app_count,
                    'limit': app_limit,
                    'can_create': app_count < app_limit
                },
                'tier_name': tier_name
            }
        
        agent_exists = await limits_repo.check_agent_exists(agent_id, account_id)
        if not agent_exists:
            return {
                'can_create': False,
                'current_count': 0,
                'limit': 0,
                'tier_name': tier_name,
                'error': 'Worker not found or access denied'
            }
        
        trigger_counts = await limits_repo.count_agent_triggers(agent_id)
        scheduled_count = trigger_counts["scheduled"]
        app_count = trigger_counts["app"]
        
        if trigger_type == 'scheduled':
            can_create = scheduled_count < scheduled_limit
            current_count = scheduled_count
            limit = scheduled_limit
        else:
            can_create = app_count < app_limit
            current_count = app_count
            limit = app_limit
        
        return {
            'can_create': can_create,
            'current_count': current_count,
            'limit': limit,
            'tier_name': tier_name
        }
        
    except Exception as e:
        logger.error(f"Error checking trigger limit for {account_id}: {e}")
        return {
            'scheduled': {'current_count': 0, 'limit': 1, 'can_create': True},
            'app': {'current_count': 0, 'limit': 2, 'can_create': True},
            'tier_name': 'free'
        }


async def check_custom_mcp_limit(account_id: str, tier_info: Optional[Dict] = None, client=None) -> Dict[str, Any]:
    try:
        tier = await _get_tier_info_if_needed(account_id, tier_info)
        tier_name = tier.get('name', 'free')
        worker_limit = tier.get('custom_workers_limit', 0)
        
        total_custom_mcps = await limits_repo.count_custom_mcps_for_account(account_id)
        can_create = total_custom_mcps < worker_limit
        
        logger.debug(f"Account {account_id} has {total_custom_mcps}/{worker_limit} custom MCPs (tier: {tier_name})")
        
        return {
            'can_create': can_create,
            'current_count': total_custom_mcps,
            'limit': worker_limit,
            'tier_name': tier_name
        }
        
    except Exception as e:
        logger.error(f"Error checking custom MCP limit for {account_id}: {e}")
        return {
            'can_create': True,
            'current_count': 0,
            'limit': 0,
            'tier_name': 'free'
        }


async def check_thread_limit(account_id: str, tier_info: Optional[Dict] = None, client=None) -> Dict[str, Any]:
    try:
        from core.agents.pipeline.slot_manager import check_thread_limit as sm_check_thread_limit
        
        result = await sm_check_thread_limit(account_id)
        tier = await _get_tier_info_if_needed(account_id, tier_info)
        
        return {
            'can_create': result.allowed,
            'current_count': result.current_count,
            'limit': result.limit,
            'tier_name': tier.get('name', 'free')
        }
        
    except Exception as e:
        logger.error(f"Error checking thread limit for {account_id}: {e}")
        return {
            'can_create': True,
            'current_count': 0,
            'limit': 2,
            'tier_name': 'free'
        }


async def get_all_limits_fast(account_id: str, tier_info: Dict) -> Dict[str, Any]:
    import time
    import asyncio
    t_start = time.time()

    tier_name = tier_info.get('name', 'free')

    thread_limit = tier_info.get('thread_limit', 2)
    project_limit = tier_info.get('project_limit', 2)
    agent_limit = tier_info.get('custom_workers_limit', 0)
    concurrent_limit = tier_info.get('concurrent_runs', 1)
    custom_mcp_limit = tier_info.get('custom_workers_limit', 0)
    scheduled_trigger_limit = tier_info.get('scheduled_triggers_limit', 0)
    app_trigger_limit = tier_info.get('app_triggers_limit', 0)

    # Try to get thread/project counts from Redis cache first (slot_manager maintains these)
    from core.services import redis as redis_service
    thread_count_cached = None
    project_count_cached = None

    try:
        thread_key = f"thread_count:{account_id}"
        project_key = f"project_count:{account_id}"
        thread_val, project_val = await asyncio.gather(
            redis_service.get(thread_key),
            redis_service.get(project_key),
            return_exceptions=True
        )
        if isinstance(thread_val, str) or isinstance(thread_val, bytes):
            thread_count_cached = int(thread_val)
        if isinstance(project_val, str) or isinstance(project_val, bytes):
            project_count_cached = int(project_val)
    except Exception:
        pass

    # If we have cached counts, use them and skip the expensive DB query for threads/projects
    if thread_count_cached is not None and project_count_cached is not None:
        # Only fetch the counts we don't have cached (agents, running_runs, custom_mcps, triggers)
        # These are less frequently needed and change less often
        counts, trigger_counts = await asyncio.gather(
            limits_repo.get_all_limits_counts(account_id),
            limits_repo.count_all_triggers_for_account(account_id)
        )
        # Use cached values for thread/project counts
        counts['thread_count'] = thread_count_cached
        counts['project_count'] = project_count_cached
        logger.debug(f"[LIMITS] {account_id[:8]}... using Redis cache for thread/project counts")
    else:
        # Cache miss - fetch from DB and warm the cache
        counts, trigger_counts = await asyncio.gather(
            limits_repo.get_all_limits_counts(account_id),
            limits_repo.count_all_triggers_for_account(account_id)
        )
        # Warm the Redis cache for next time
        try:
            from core.agents.pipeline.slot_manager import warm_all_caches
            asyncio.create_task(warm_all_caches(
                account_id,
                thread_count=counts['thread_count'],
                project_count=counts['project_count']
            ))
        except Exception:
            pass

    logger.info(f"[LIMITS] {account_id[:8]}... threads={counts['thread_count']}/{thread_limit} projects={counts['project_count']}/{project_limit} can_create_thread={counts['thread_count'] < thread_limit}")

    logger.debug(f"⚡ All limits fetched in {(time.time() - t_start) * 1000:.1f}ms")
    
    return {
        'threads': {
            'current_count': counts['thread_count'],
            'limit': thread_limit,
            'can_create': counts['thread_count'] < thread_limit,
            'tier_name': tier_name
        },
        'projects': {
            'current_count': counts['project_count'],
            'limit': project_limit,
            'can_create': counts['project_count'] < project_limit,
            'tier_name': tier_name
        },
        'agents': {
            'current_count': counts['agent_count'],
            'limit': agent_limit,
            'can_create': counts['agent_count'] < agent_limit,
            'tier_name': tier_name
        },
        'concurrent_runs': {
            'running_count': counts['running_runs_count'],
            'limit': concurrent_limit,
            'can_start': counts['running_runs_count'] < concurrent_limit,
            'tier_name': tier_name
        },
        'custom_mcps': {
            'current_count': counts['custom_mcp_count'],
            'limit': custom_mcp_limit,
            'can_create': counts['custom_mcp_count'] < custom_mcp_limit,
            'tier_name': tier_name
        },
        'triggers': {
            'scheduled': {
                'current_count': trigger_counts.get('scheduled', 0),
                'limit': scheduled_trigger_limit,
                'can_create': trigger_counts.get('scheduled', 0) < scheduled_trigger_limit
            },
            'app': {
                'current_count': trigger_counts.get('app', 0),
                'limit': app_trigger_limit,
                'can_create': trigger_counts.get('app', 0) < app_trigger_limit
            },
            'tier_name': tier_name
        }
    }