Skip to content

The open alternative to Salesforce, designed for AI.

3.8 KB
Raw Blame
import { Injectable } from '@nestjs/common';

import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';

import { RedisClientService } from 'src/engine/core-modules/redis-client/redis-client.service';
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';

const STREAM_CHUNKS_TTL_SECONDS = 3600;

const RESET_OWNED_STREAM_STATE_SCRIPT = `
if redis.call('GET', KEYS[2]) == ARGV[1] then
  redis.call('DEL', KEYS[1], KEYS[2])
end`;

@Injectable()
export class AgentChatEventPublisherService {
  constructor(
    private readonly subscriptionService: SubscriptionService,
    private readonly redisClientService: RedisClientService,
  ) {}

  private getStreamChunksKey(threadId: string): string {
    return `agent-chat-stream-chunks:${threadId}`;
  }

  private getStreamOwnerKey(threadId: string): string {
    return `agent-chat-stream-owner:${threadId}`;
  }

  async publish({
    threadId,
    workspaceId,
    event,
    shouldKeepCatchup = true,
  }: {
    threadId: string;
    workspaceId: string;
    event: AgentChatSubscriptionEvent;
    // a run channel is followed from before its run starts, so nothing reads catch-up chunks for it
    shouldKeepCatchup?: boolean;
  }): Promise<void> {
    const publishedEvent = shouldKeepCatchup
      ? await this.keepCatchup({ threadId, event })
      : event;

    await this.subscriptionService.publishToAgentChat({
      workspaceId,
      threadId,
      payload: {
        onAgentChatEvent: {
          threadId,
          event: publishedEvent,
        },
      },
    });
  }

  private async keepCatchup({
    threadId,
    event,
  }: {
    threadId: string;
    event: AgentChatSubscriptionEvent;
  }): Promise<AgentChatSubscriptionEvent> {
    const redis = this.redisClientService.getClient();
    const key = this.getStreamChunksKey(threadId);

    if (event.type === 'stream-chunk') {
      // Sent together on one connection, Redis still runs them in order.
      const [seq] = await Promise.all([
        redis.rpush(key, JSON.stringify(event.chunk)),
        redis.expire(key, STREAM_CHUNKS_TTL_SECONDS),
        redis.expire(
          this.getStreamOwnerKey(threadId),
          STREAM_CHUNKS_TTL_SECONDS,
        ),
      ]);

      return { ...event, seq };
    }

    if (
      event.type === 'message-persisted' ||
      event.type === 'credits-exhausted'
    ) {
      await redis.del(key);
    }

    return event;
  }

  async resetStreamState(threadId: string): Promise<void> {
    const redis = this.redisClientService.getClient();

    await redis.del(this.getStreamChunksKey(threadId));
  }

  async startStreamState({
    threadId,
    streamId,
  }: {
    threadId: string;
    streamId: string;
  }): Promise<void> {
    await this.redisClientService
      .getClient()
      .multi()
      .del(this.getStreamChunksKey(threadId))
      .set(
        this.getStreamOwnerKey(threadId),
        streamId,
        'EX',
        STREAM_CHUNKS_TTL_SECONDS,
      )
      .exec();
  }

  // a stale release of a dead stream must not delete the chunks of the stream that started after it
  async resetOwnedStreamState({
    threadId,
    streamId,
  }: {
    threadId: string;
    streamId: string;
  }): Promise<void> {
    await this.redisClientService
      .getClient()
      .eval(
        RESET_OWNED_STREAM_STATE_SCRIPT,
        2,
        this.getStreamChunksKey(threadId),
        this.getStreamOwnerKey(threadId),
        streamId,
      );
  }

  async getAccumulatedChunks(threadId: string): Promise<{
    chunks: Record<string, unknown>[];
    maxSeq: number;
  }> {
    const redis = this.redisClientService.getClient();
    const rawChunks = await redis.lrange(
      this.getStreamChunksKey(threadId),
      0,
      -1,
    );

    return {
      chunks: rawChunks.map((raw) => JSON.parse(raw)),
      maxSeq: rawChunks.length,
    };
  }
}