Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

7.6 KB
Raw Blame
import { throwOnErr } from '@core/util/result';
import type { GithubPullRequestLabel } from '@entity/types/entity';
import { authServiceClient } from '@service-auth/client';
import type {
  EnrichedGithubPullRequest,
  GithubPullRequestRef,
} from '@service-auth/generated/schemas';
import { storageServiceClient } from '@service-storage/client';
import type {
  GithubPullRequest,
  GithubPullRequestsResponse,
} from '@service-storage/generated/schemas';
import {
  type QueryFunctionContext,
  type QueryKey,
  useQuery,
} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import {
  documentGithubPullRequestsKeys,
  githubPullRequestRefreshKeys,
} from './keys';

const DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME = 60 * 1000;
const GITHUB_PULL_REQUEST_REFRESH_STALE_TIME = 5 * 60 * 1000;

type DocumentIdInput =
  | string
  | null
  | undefined
  | Accessor<string | null | undefined>;
type EnabledInput = boolean | Accessor<boolean>;

type FetchDocumentGithubPullRequestsOptions = {
  onInitialResponse?: (response: GithubPullRequestsResponse) => void;
};

function readDocumentId(
  documentId: DocumentIdInput
): string | null | undefined {
  return typeof documentId === 'function' ? documentId() : documentId;
}

function readEnabled(enabled: EnabledInput | undefined): boolean {
  if (enabled === undefined) return true;
  return typeof enabled === 'function' ? enabled() : enabled;
}

/**
 * Storage pull request extended with enrichment-only fields. The documents
 * service doesn't expose body/author/labels yet, so they only arrive via the
 * live enrich merge or stored metadata and must stay optional.
 */
export type GithubPullRequestWithDetails = GithubPullRequest & {
  description?: string | null;
  authorLogin?: string | null;
  labels?: GithubPullRequestLabel[] | null;
  /** Whether the pull request is a draft. Absent when the source did not say. */
  draft?: boolean;
};

function toGithubPullRequestRef(
  pullRequest: GithubPullRequest
): GithubPullRequestRef {
  return {
    displayName: pullRequest.displayName,
    githubKey: pullRequest.githubKey,
    number: pullRequest.number,
    owner: pullRequest.owner,
    repo: pullRequest.repo,
    url: pullRequest.url,
  };
}

function toStorageGithubPullRequest(
  pullRequest: EnrichedGithubPullRequest,
  fallbackPullRequest: GithubPullRequestWithDetails | undefined
): GithubPullRequestWithDetails {
  return {
    additions: pullRequest.additions ?? fallbackPullRequest?.additions,
    authorLogin: pullRequest.authorLogin ?? fallbackPullRequest?.authorLogin,
    description: pullRequest.description ?? fallbackPullRequest?.description,
    checks: pullRequest.checks ?? fallbackPullRequest?.checks,
    comments: pullRequest.comments ?? fallbackPullRequest?.comments,
    deletions: pullRequest.deletions ?? fallbackPullRequest?.deletions,
    displayName: pullRequest.displayName,
    foreignEntityId: fallbackPullRequest?.foreignEntityId,
    githubKey: pullRequest.githubKey,
    name: pullRequest.name ?? fallbackPullRequest?.name,
    number: pullRequest.number,
    owner: pullRequest.owner,
    repo: pullRequest.repo,
    status: pullRequest.status ?? fallbackPullRequest?.status,
    url: pullRequest.url,
  };
}

function createPullRequestFallbacksByKey(
  pullRequests: GithubPullRequest[]
): Map<string, GithubPullRequest> {
  return new Map(
    pullRequests.map((pullRequest) => [pullRequest.githubKey, pullRequest])
  );
}

function hasStoredEnrichedGithubPullRequestData(
  pullRequest: GithubPullRequest
): boolean {
  return (
    pullRequest.additions != null ||
    pullRequest.checks != null ||
    pullRequest.comments != null ||
    pullRequest.deletions != null ||
    pullRequest.name != null ||
    pullRequest.status != null
  );
}

function hasStoredEnrichedGithubPullRequests(
  response: GithubPullRequestsResponse
): boolean {
  return response.pullRequests.some(hasStoredEnrichedGithubPullRequestData);
}

export type GithubPullRequestsWithDetailsResponse = {
  pullRequests: GithubPullRequestWithDetails[];
};

export async function fetchDocumentGithubPullRequests(
  documentId: string,
  options?: FetchDocumentGithubPullRequestsOptions
): Promise<GithubPullRequestsWithDetailsResponse> {
  const rawResponse = await throwOnErr(() =>
    storageServiceClient.getDocumentGithubPullRequests({ documentId })
  );

  if (rawResponse.pullRequests.length === 0) {
    return rawResponse;
  }

  if (hasStoredEnrichedGithubPullRequests(rawResponse)) {
    options?.onInitialResponse?.(rawResponse);
  }

  const enrichedResponse = await authServiceClient.enrichGithubPullRequests({
    pullRequests: rawResponse.pullRequests.map(toGithubPullRequestRef),
  });

  if (enrichedResponse.isErr()) {
    return rawResponse;
  }

  const fallbackPullRequestsByKey = createPullRequestFallbacksByKey(
    rawResponse.pullRequests
  );

  const mergedResponse = {
    pullRequests: enrichedResponse.value.pullRequests.map(
      (pullRequest, index) =>
        toStorageGithubPullRequest(
          pullRequest,
          fallbackPullRequestsByKey.get(pullRequest.githubKey) ??
            rawResponse.pullRequests[index]
        )
    ),
  };
  return mergedResponse;
}

// Cached callbacks outlive the caller; only the resolved id enters them.
function documentGithubPullRequestsQueryOptions(
  documentId: string | null | undefined,
  enabled: boolean
) {
  const queryKey = documentId
    ? documentGithubPullRequestsKeys.list(documentId).queryKey
    : documentGithubPullRequestsKeys.list._def;

  return {
    queryKey,
    queryFn: ({ client }: QueryFunctionContext) => {
      if (!documentId) {
        throw new Error(
          'Document ID is required to fetch GitHub pull requests'
        );
      }
      return fetchDocumentGithubPullRequests(documentId, {
        onInitialResponse: (initialResponse) => {
          client.setQueryData(queryKey, initialResponse);
        },
      });
    },
    staleTime: DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME,
    enabled: !!documentId && enabled,
  };
}

export function useDocumentGithubPullRequestsQuery(
  documentId: DocumentIdInput,
  enabled?: EnabledInput
) {
  return useQuery(() =>
    documentGithubPullRequestsQueryOptions(
      readDocumentId(documentId),
      readEnabled(enabled)
    )
  );
}

// Cached callbacks outlive the caller, so the refresh takes the reference and
// the keys to invalidate as plain values, never the caller's closures.
function githubPullRequestRefreshQueryOptions(
  reference: GithubPullRequestRef | undefined,
  refreshedKeys: readonly QueryKey[]
) {
  return {
    queryKey: githubPullRequestRefreshKeys.refresh(reference?.githubKey ?? '')
      .queryKey,
    enabled: reference !== undefined,
    queryFn: async ({ client }: QueryFunctionContext) => {
      const result = await authServiceClient.enrichGithubPullRequests({
        pullRequests: [reference!],
      });
      if (result.isErr()) return false;
      for (const queryKey of refreshedKeys) {
        client.invalidateQueries({ queryKey });
      }
      return true;
    },
    staleTime: GITHUB_PULL_REQUEST_REFRESH_STALE_TIME,
    retry: false,
    refetchOnWindowFocus: false,
  };
}

/**
 * Refresh one pull request from GitHub with the viewer's linked account, which
 * rewrites every stored copy, then invalidate `refreshedKeys` so readers of the
 * stored copy load it again. Without a linked account, or when GitHub is
 * unavailable, the stored copy stays as it is.
 */
export function useRefreshGithubPullRequest(
  pullRequest: Accessor<GithubPullRequestRef | undefined>,
  refreshedKeys: Accessor<readonly QueryKey[]>
) {
  return useQuery(() =>
    githubPullRequestRefreshQueryOptions(pullRequest(), refreshedKeys())
  );
}