# All files / src/db/repositories/drizzle account.ts

2.17% Statements 1/46
0% Branches 0/24
7.14% Functions 1/14
2.17% Lines 1/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    80x

     /**
     * Drizzle Account Repository Adapter
     *
     * Implements AccountRepository interface using Drizzle ORM.
     * Handles round-robin selection via lastUsedAt ordering
     * and automatic exhaustion expiry.
     */

    import { eq, and, asc, lte } from 'drizzle-orm';
    import { nanoid } from 'nanoid';
    import type { DrizzleDatabase } from '../../index.js';
    import { accounts, agents, type Account } from '../../schema.js';
    import type { AccountRepository, CreateAccountData } from '../account-repository.js';

    export class DrizzleAccountRepository implements AccountRepository {
      constructor(private db: DrizzleDatabase) {}

      async create(data: CreateAccountData): Promise<Account> {
        const id = nanoid();
        const now = new Date();

        const [created] = await this.db.insert(accounts).values({
          id,
          email: data.email,
          provider: data.provider ?? 'claude',
          configJson: data.configJson ?? null,
          credentials: data.credentials ?? null,
          isExhausted: false,
          exhaustedUntil: null,
          lastUsedAt: null,
          sortOrder: 0,
          createdAt: now,
          updatedAt: now,
        }).returning();

        return created;
      }

      async findById(id: string): Promise<Account | null> {
        const result = await this.db
          .select()
          .from(accounts)
          .where(eq(accounts.id, id))
          .limit(1);
        return result[0] ?? null;
      }

      async findByEmail(email: string): Promise<Account | null> {
        const result = await this.db
          .select()
          .from(accounts)
          .where(eq(accounts.email, email))
          .limit(1);
        return result[0] ?? null;
      }

      async findByProvider(provider: string): Promise<Account[]> {
        return this.db
          .select()
          .from(accounts)
          .where(eq(accounts.provider, provider));
      }

      async findNextAvailable(provider: string): Promise<Account | null> {
        await this.clearExpiredExhaustion();

        const result = await this.db
          .select()
          .from(accounts)
          .where(
            and(
              eq(accounts.provider, provider),
              eq(accounts.isExhausted, false),
            ),
          )
          .orderBy(asc(accounts.lastUsedAt))
          .limit(1);

        return result[0] ?? null;
      }

      async markExhausted(id: string, until: Date): Promise<Account> {
        const now = new Date();
        const [updated] = await this.db
          .update(accounts)
          .set({
            isExhausted: true,
            exhaustedUntil: until,
            updatedAt: now,
          })
          .where(eq(accounts.id, id))
          .returning();

        if (!updated) {
          throw new Error(`Account not found: ${id}`);
        }

        return updated;
      }

      async markAvailable(id: string): Promise<Account> {
        const now = new Date();
        const [updated] = await this.db
          .update(accounts)
          .set({
            isExhausted: false,
            exhaustedUntil: null,
            updatedAt: now,
          })
          .where(eq(accounts.id, id))
          .returning();

        if (!updated) {
          throw new Error(`Account not found: ${id}`);
        }

        return updated;
      }

      async updateLastUsed(id: string): Promise<Account> {
        const now = new Date();
        const [updated] = await this.db
          .update(accounts)
          .set({ lastUsedAt: now, updatedAt: now })
          .where(eq(accounts.id, id))
          .returning();

        if (!updated) {
          throw new Error(`Account not found: ${id}`);
        }

        return updated;
      }

      async clearExpiredExhaustion(): Promise<number> {
        const now = new Date();

        const cleared = await this.db
          .update(accounts)
          .set({
            isExhausted: false,
            exhaustedUntil: null,
            updatedAt: now,
          })
          .where(
            and(
              eq(accounts.isExhausted, true),
              lte(accounts.exhaustedUntil, now),
            ),
          )
          .returning({ id: accounts.id });

        return cleared.length;
      }

      async findAll(): Promise<Account[]> {
        return this.db.select().from(accounts);
      }

      async updateCredentials(id: string, credentials: string): Promise<Account> {
        const now = new Date();
        const [updated] = await this.db
          .update(accounts)
          .set({ credentials, updatedAt: now })
          .where(eq(accounts.id, id))
          .returning();

        if (!updated) {
          throw new Error(`Account not found: ${id}`);
        }

        return updated;
      }

      async updateAccountAuth(id: string, configJson: string, credentials: string): Promise<Account> {
        const now = new Date();
        const [updated] = await this.db
          .update(accounts)
          .set({ configJson, credentials, updatedAt: now })
          .where(eq(accounts.id, id))
          .returning();

        if (!updated) {
          throw new Error(`Account not found: ${id}`);
        }

        return updated;
      }

      async delete(id: string): Promise<void> {
        // Manually nullify agent FK — the migration lacks ON DELETE SET NULL
        await this.db
          .update(agents)
          .set({ accountId: null })
          .where(eq(agents.accountId, id));

        const [deleted] = await this.db.delete(accounts).where(eq(accounts.id, id)).returning();

        if (!deleted) {
          throw new Error(`Account not found: ${id}`);
        }
      }
    }