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.

8.2 KB
Raw Blame
import { SYNC_SERVICE_HOSTS } from '@core/constant/servers';
import { getPermissionToken } from '@core/signal/token';
import {
  type FetchWithTokenErrorCode,
  fetchWithToken,
} from '@core/util/fetchWithToken';
import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import { InitializeFromSnapshotRequest } from '@macro-inc/collaboration/sync-service/generated/schema';
import type { SerializedEditorState } from 'lexical';
import { err, ok, type Result } from 'neverthrow';
import type { BlameRow, DocumentMetadata } from './generated/http/schemas';

const SYNC_SERVICE_WORKER_URL = `${SYNC_SERVICE_HOSTS['worker']}`;

const SYNC_ORIGIN =
  import.meta.env.MODE === 'development'
    ? 'https://dev.macro.com'
    : 'https://macro.com';

const WAKEUP_TTL = 55 * 1000;
const WAKEUP_DEBOUNCE_MS = 200;

const pendingWakeups = new Map<
  string,
  { debounceTimer: ReturnType<typeof setTimeout>; idleTaskId?: number }
>();
const recentWakeups = new Map<string, number>();

const scheduleIdleTask =
  typeof window !== 'undefined' && window.requestIdleCallback
    ? (cb: () => void) => window.requestIdleCallback(cb)
    : (cb: () => void) => window.setTimeout(cb, 0) as unknown as number;

const cancelIdleTask =
  typeof window !== 'undefined' && window.cancelIdleCallback
    ? (id: number) => window.cancelIdleCallback(id)
    : (id: number) =>
        window.clearTimeout(id as unknown as ReturnType<typeof setTimeout>);

function syncFetch(
  url: string,
  init?: SafeFetchInit
): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
function syncFetch<T extends ObjectLike>(
  url: string,
  init?: SafeFetchInit
): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
function syncFetch<T extends ObjectLike = never>(
  url: string,
  init?: SafeFetchInit
):
  | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
  | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
  return fetchWithToken<T>(`${SYNC_SERVICE_WORKER_URL}${url}`, {
    ...init,
    headers: {
      ...init?.headers,
      ...(isTauri() && { Origin: SYNC_ORIGIN }),
    },
  });
}

export type HistorySession = {
  userId: string;
  startMs: number;
  endMs: number;
  count: number;
};

/** A single frontier op-id — structurally a `SyncServiceVersionID`, so it can
 * be passed straight to the copy/fork path. */
export type HistoryVersionId = {
  peer: string;
  counter: number;
};

export const syncServiceClient = {
  async wakeup(args: { documentId: string }) {
    await syncFetch(`/document/${args.documentId}/wakeup`, {
      method: 'GET',
    });
  },
  safeWakeup(id: string) {
    const lastWakeup = recentWakeups.get(id);
    if (lastWakeup && Date.now() - lastWakeup < WAKEUP_TTL) {
      return;
    }

    const existing = pendingWakeups.get(id);
    if (existing) {
      return;
    }

    const debounceTimer = setTimeout(() => {
      const pending = pendingWakeups.get(id);
      if (!pending) return;

      const idleTaskId = scheduleIdleTask(async () => {
        try {
          await syncFetch(`/document/${id}/wakeup`, {
            method: 'GET',
          });
          recentWakeups.set(id, Date.now());

          const now = Date.now();
          for (const [key, timestamp] of recentWakeups.entries()) {
            if (now - timestamp >= WAKEUP_TTL) {
              recentWakeups.delete(key);
            }
          }
        } catch (error) {
          console.error(`Failed to wakeup document ${id}:`, error);
        } finally {
          pendingWakeups.delete(id);
        }
      });

      pendingWakeups.set(id, { debounceTimer, idleTaskId });
    }, WAKEUP_DEBOUNCE_MS);

    pendingWakeups.set(id, { debounceTimer });
  },
  cancelWakeup(id: string) {
    const pending = pendingWakeups.get(id);
    if (pending) {
      clearTimeout(pending.debounceTimer);
      if (pending.idleTaskId !== undefined) {
        cancelIdleTask(pending.idleTaskId);
      }
      pendingWakeups.delete(id);
    }
  },
  async exists(args: { documentId: string }) {
    const res = await syncFetch(`/document/${args.documentId}/exists`, {
      method: 'HEAD',
    });

    if (res.isErr()) {
      if (
        res.isErr() &&
        res.error.some((error) => error.code === 'NOT_FOUND')
      ) {
        return ok({ exists: false });
      }
      return res;
    }

    return ok({ exists: true });
  },
  async initializeFromSnapshot(args: {
    documentId: string;
    snapshot: Uint8Array;
  }) {
    const token = await getPermissionToken('document', args.documentId);
    const req = InitializeFromSnapshotRequest.encode({
      snapshot: args.snapshot,
    }) as Uint8Array<ArrayBuffer>;

    return await syncFetch(`/document/${args.documentId}/initialize`, {
      headers: {
        'Content-Type': 'application/octet-stream',
        Authorization: `Bearer ${token}`,
      },
      method: 'POST',
      body: req,
    });
  },
  async getDocumentMetadata(args: { documentId: string }) {
    const token = await getPermissionToken('document', args.documentId);

    const response = await syncFetch<DocumentMetadata>(
      `/document/${args.documentId}/metadata`,
      {
        headers: {
          'Content-Type': 'application/octet-stream',
          Authorization: `Bearer ${token}`,
        },
        method: 'GET',
      }
    );
    if (response.isErr()) {
      return err(response.error);
    }

    return ok(response.value);
  },
  /**
   * Look up who last edited a given Lexical node and when. `user_id` is a
   * MacroId resolved server-side; `null` if the peer has no recorded user
   * (anonymous edits or legacy data not yet mirrored locally). `actor` is the
   * signed agent actor (`bot|<uuid>`) the peer edited as, null for humans.
   */
  async getNodeBlame(args: { documentId: string; nodeId: string }) {
    const token = await getPermissionToken('document', args.documentId);

    const response = await syncFetch<BlameRow>(
      `/document/${args.documentId}/blame/${args.nodeId}`,
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        method: 'GET',
      }
    );

    if (response.isErr()) {
      return err(response.error);
    }
    const { peer_id, user_id, actor, timestamp_ms } = response.value;
    return ok({
      peerId: peer_id,
      userId: user_id ?? null,
      actor: actor ?? null,
      editedAt: new Date(timestamp_ms),
    });
  },
  async getSnapshot(args: { documentId: string }) {
    const token = await getPermissionToken('document', args.documentId);
    const response = await platformFetch(
      `${SYNC_SERVICE_WORKER_URL}/document/${args.documentId}/snapshot`,
      {
        headers: {
          'Content-Type': 'application/octet-stream',
          Authorization: `Bearer ${token}`,
          ...(isTauri() && { Origin: SYNC_ORIGIN }),
        },
        method: 'GET',
      }
    );

    // Without this an error body decodes as a snapshot, surfacing as a bogus
    // Loro parse failure. Transport failures (offline, CORS) reject instead,
    // which callers already see.
    if (!response.ok) {
      return err([
        {
          code: 'SNAPSHOT_HTTP_ERROR',
          message: `The sync service returned HTTP ${response.status}.`,
        },
      ]);
    }

    const data = await response.arrayBuffer();

    const array = new Uint8Array(data);

    return ok(array);
  },
  async getRaw(args: { documentId: string }): Promise<SerializedEditorState> {
    const token = await getPermissionToken('document', args.documentId);
    const response = await platformFetch(
      `${SYNC_SERVICE_WORKER_URL}/document/${args.documentId}/raw`,
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
          ...(isTauri() && { Origin: SYNC_ORIGIN }),
        },
        method: 'GET',
      }
    );
    if (!response.ok) {
      try {
        console.error('Failed to fetch raw document', await response.text());
      } catch (_e) {
        console.error('Failed to fetch raw document');
      }
      throw new Error('Failed to fetch raw document');
    }
    const state = await response.json();
    return state;
  },
};