sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ Vault/ MattersExport.ts

import * as vault from "@distilled.cloud/gcp/vault_v1";
import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { GcpEnvironment } from "../Environment.ts";
import type { Providers } from "../Providers.ts";
import {
  encodeOwnershipLine,
  findExportByName,
  findOwnedExport,
  getExport,
  hasOwnershipMarker,
  ignoreMissing,
  jsonEqual,
  listActiveMatters,
  listExports,
  MAX_EXPORT_NAME_LENGTH,
  ownedByAlchemy,
  ownershipLabels,
  parseOwnership,
  toGeneratedName,
} from "./internal.ts";

export type MattersExportProps = {
  /**
   * Parent matter id. Immutable — changing it replaces the export.
   */
  matterId: string;
  /**
   * Server-assigned export id. Leave blank on create. Immutable —
   * changing it replaces the export.
   */
  exportId?: string;
  /**
   * Export name (max 100 characters including Alchemy's ownership
   * marker). Do not use `~!
		
		
		
		
	

(),;@:/?`. Vault exports have no labels
   * field, so ownership is stored in a `[alchemy …]` prefix and stripped
   * from attributes. Vault has no export update API — changing the name
   * replaces the export.
   */
  name?: string;
  /**
   * Search query used to create the export. Required on create. Vault
   * has no export update API — changing the query replaces the export.
   */
  query: vault.Query;
  /**
   * Additional export options (format, region). Vault has no export
   * update API — changing options replaces the export.
   */
  exportOptions?: vault.ExportOptions;
};

export type MattersExport = Resource<
  "GCP.Vault.MattersExport",
  MattersExportProps,
  {
    /** Server-assigned export id. */
    exportId: string;
    /** Parent matter id. */
    matterId: string;
    /** Project id used when the export was reconciled. */
    project: string;
    /** User-facing name with the Alchemy ownership prefix stripped. */
    name: string | undefined;
    /** Search query. */
    query: vault.Query | undefined;
    /** Export options. */
    exportOptions: vault.ExportOptions | undefined;
    /** Export status (`IN_PROGRESS`, `COMPLETED`, `FAILED`). */
    status: string | undefined;
    /** RFC3339 create timestamp. */
    createTime: string | undefined;
    /** Parent export id when this is a child export. */
    parentExportId: string | undefined;
    /** Cloud Storage sink for export files. */
    cloudStorageSink: vault.CloudStorageSink | undefined;
    /** Progress and size. */
    stats: vault.ExportStats | undefined;
  },
  never,
  Providers
>;

/**
 * A Google Vault export on a matter.
 *
 * Vault exports have no labels field, so Alchemy stamps ownership into
 * `name` for `list` / nuke. There is no update API — changing the query,
 * options, or name replaces the export (delete-first).
 *
 * ### Creating an Export
 * **Example:** Mail export
 * ```typescript
 * const exported = yield* GCP.Vault.MattersExport("Mail", {
 *   matterId: matter.matterId,
 *   query: {
 *     corpus: "MAIL",
 *     dataScope: "ALL_DATA",
 *     searchMethod: "ACCOUNT",
 *     accountInfo: { emails: ["user@example.com"] },
 *   },
 *   exportOptions: { mailOptions: { exportFormat: "MBOX" } },
 * });
 * ```
 *
 * **Example:** Drive export with a name
 * ```typescript
 * const exported = yield* GCP.Vault.MattersExport("Drive", {
 *   matterId: matter.matterId,
 *   name: "drive-dump",
 *   query: {
 *     corpus: "DRIVE",
 *     dataScope: "HELD_DATA",
 *     searchMethod: "ENTIRE_ORG",
 *   },
 * });
 * ```
 *
 * @resource
 * @category Vault
 */
export const MattersExport = Resource<MattersExport>("GCP.Vault.MattersExport");

export class MattersExportNotResolved extends Data.TaggedError(
  "GCP.Vault.MattersExportNotResolved",
)<{
  matterId: string;
  exportId: string;
}> {}

const toAttrs = (item: vault.Export, project: string) => ({
  exportId: item.id ?? "",
  matterId: item.matterId ?? "",
  project,
  name: parseOwnership(item.name).text,
  query: item.query,
  exportOptions: item.exportOptions,
  status: item.status,
  createTime: item.createTime,
  parentExportId: item.parentExportId,
  cloudStorageSink: item.cloudStorageSink,
  stats: item.stats,
});

export const MattersExportProvider = () =>
  Provider.succeed(MattersExport, {
    stables: ["exportId", "matterId", "project", "createTime"],

    diff: Effect.fn(function* ({ news, olds, output }) {
      if (!isResolved(news)) return undefined;
      const previousMatter = olds?.matterId ?? output?.matterId;
      if (previousMatter !== undefined && news.matterId !== previousMatter) {
        return { action: "replace" as const, deleteFirst: true };
      }
      const previousId = olds?.exportId ?? output?.exportId;
      if (previousId !== undefined && news.exportId !== undefined && news.exportId !== previousId) {
        return { action: "replace" as const, deleteFirst: true };
      }
      const previousName = olds?.name ?? output?.name;
      if (news.name !== undefined && previousName !== undefined && news.name !== previousName) {
        return { action: "replace" as const, deleteFirst: true };
      }
      const previousQuery = olds?.query ?? output?.query;
      if (previousQuery !== undefined && !jsonEqual(previousQuery, news.query)) {
        return { action: "replace" as const, deleteFirst: true };
      }
      const previousOptions = olds?.exportOptions ?? output?.exportOptions;
      if (
        news.exportOptions !== undefined &&
        previousOptions !== undefined &&
        !jsonEqual(previousOptions, news.exportOptions)
      ) {
        return { action: "replace" as const, deleteFirst: true };
      }
      return undefined;
    }),

    read: Effect.fn(function* ({ id, olds, output, previous }) {
      const env = yield* GcpEnvironment.current;
      const matterId = olds?.matterId ?? output?.matterId ?? "";
      const exportId = olds?.exportId ?? output?.exportId ?? "";
      let existing = yield* getExport(matterId, exportId);
      if (existing === undefined) {
        const ownership = yield* ownershipLabels(id);
        const name = encodeOwnershipLine(
          ownership,
          olds?.name ?? output?.name,
          MAX_EXPORT_NAME_LENGTH,
        );
        existing = yield* findExportByName(matterId, name);
      }
      if (existing === undefined) {
        existing = yield* findOwnedExport(id, matterId);
      }
      if (existing === undefined) return undefined;
      const attrs = toAttrs(existing, env.project);
      return (yield* ownedByAlchemy(id, existing.name))
        ? attrs
        : unownedUnlessPrevious(attrs, previous, "exportId");
    }),

    list: () =>
      Effect.gen(function* () {
        const env = yield* GcpEnvironment.current;
        const matters = yield* listActiveMatters();
        const pages = yield* Effect.forEach(
          matters,
          (matter) =>
            listExports(matter.matterId ?? "").pipe(
              Effect.map((items) =>
                items
                  .filter((item) => hasOwnershipMarker(item.name))
                  .map((item) => toAttrs(item, env.project)),
              ),
            ),
          { concurrency: 4 },
        );
        return pages.flat();
      }),

    reconcile: Effect.fn(function* ({ id, news, output }) {
      const env = yield* GcpEnvironment.current;
      const matterId = news.matterId;
      const ownership = yield* ownershipLabels(id);
      const displayName = yield* toGeneratedName(id, news.name, output?.name, 40);
      const name = encodeOwnershipLine(ownership, displayName, MAX_EXPORT_NAME_LENGTH);
      const desired: vault.Export = {
        name,
        query: news.query,
        exportOptions: news.exportOptions,
      };

      let current = yield* getExport(matterId, news.exportId ?? output?.exportId ?? "");
      if (current === undefined) {
        current = yield* findExportByName(matterId, name);
      }
      if (current === undefined) {
        current = yield* findOwnedExport(id, matterId);
      }

      if (current === undefined) {
        const created = yield* vault
          .createMattersExports({
            matterId,
            body: desired,
          })
          .pipe(Effect.catchTag("Conflict", () => findExportByName(matterId, name)));
        current = created ?? undefined;
      }

      if (current === undefined) {
        return yield* new MattersExportNotResolved({
          matterId,
          exportId: news.exportId ?? output?.exportId ?? name,
        });
      }

      return toAttrs(current, env.project);
    }),

    delete: Effect.fn(function* ({ output }) {
      if (output.matterId.length === 0 || output.exportId.length === 0) {
        return;
      }
      yield* ignoreMissing(
        vault.deleteMattersExports({
          matterId: output.matterId,
          exportId: output.exportId,
        }),
      );
    }),
  });
(),;@:/?`. Vault exports have no labels\n * field, so ownership is stored in a `[alchemy …]` prefix and stripped\n * from attributes. Vault has no export update API — changing the name\n * replaces the export.\n */\n name?: string;\n /**\n * Search query used to create the export. Required on create. Vault\n * has no export update API — changing the query replaces the export.\n */\n query: vault.Query;\n /**\n * Additional export options (format, region). Vault has no export\n * update API — changing options replaces the export.\n */\n exportOptions?: vault.ExportOptions;\n};\n\nexport type MattersExport = Resource\u003c\n \"GCP.Vault.MattersExport\",\n MattersExportProps,\n {\n /** Server-assigned export id. */\n exportId: string;\n /** Parent matter id. */\n matterId: string;\n /** Project id used when the export was reconciled. */\n project: string;\n /** User-facing name with the Alchemy ownership prefix stripped. */\n name: string | undefined;\n /** Search query. */\n query: vault.Query | undefined;\n /** Export options. */\n exportOptions: vault.ExportOptions | undefined;\n /** Export status (`IN_PROGRESS`, `COMPLETED`, `FAILED`). */\n status: string | undefined;\n /** RFC3339 create timestamp. */\n createTime: string | undefined;\n /** Parent export id when this is a child export. */\n parentExportId: string | undefined;\n /** Cloud Storage sink for export files. */\n cloudStorageSink: vault.CloudStorageSink | undefined;\n /** Progress and size. */\n stats: vault.ExportStats | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * A Google Vault export on a matter.\n *\n * Vault exports have no labels field, so Alchemy stamps ownership into\n * `name` for `list` / nuke. There is no update API — changing the query,\n * options, or name replaces the export (delete-first).\n *\n * ### Creating an Export\n * **Example:** Mail export\n * ```typescript\n * const exported = yield* GCP.Vault.MattersExport(\"Mail\", {\n * matterId: matter.matterId,\n * query: {\n * corpus: \"MAIL\",\n * dataScope: \"ALL_DATA\",\n * searchMethod: \"ACCOUNT\",\n * accountInfo: { emails: [\"user@example.com\"] },\n * },\n * exportOptions: { mailOptions: { exportFormat: \"MBOX\" } },\n * });\n * ```\n *\n * **Example:** Drive export with a name\n * ```typescript\n * const exported = yield* GCP.Vault.MattersExport(\"Drive\", {\n * matterId: matter.matterId,\n * name: \"drive-dump\",\n * query: {\n * corpus: \"DRIVE\",\n * dataScope: \"HELD_DATA\",\n * searchMethod: \"ENTIRE_ORG\",\n * },\n * });\n * ```\n *\n * @resource\n * @category Vault\n */\nexport const MattersExport = Resource\u003cMattersExport>(\"GCP.Vault.MattersExport\");\n\nexport class MattersExportNotResolved extends Data.TaggedError(\n \"GCP.Vault.MattersExportNotResolved\",\n)\u003c{\n matterId: string;\n exportId: string;\n}> {}\n\nconst toAttrs = (item: vault.Export, project: string) => ({\n exportId: item.id ?? \"\",\n matterId: item.matterId ?? \"\",\n project,\n name: parseOwnership(item.name).text,\n query: item.query,\n exportOptions: item.exportOptions,\n status: item.status,\n createTime: item.createTime,\n parentExportId: item.parentExportId,\n cloudStorageSink: item.cloudStorageSink,\n stats: item.stats,\n});\n\nexport const MattersExportProvider = () =>\n Provider.succeed(MattersExport, {\n stables: [\"exportId\", \"matterId\", \"project\", \"createTime\"],\n\n diff: Effect.fn(function* ({ news, olds, output }) {\n if (!isResolved(news)) return undefined;\n const previousMatter = olds?.matterId ?? output?.matterId;\n if (previousMatter !== undefined && news.matterId !== previousMatter) {\n return { action: \"replace\" as const, deleteFirst: true };\n }\n const previousId = olds?.exportId ?? output?.exportId;\n if (previousId !== undefined && news.exportId !== undefined && news.exportId !== previousId) {\n return { action: \"replace\" as const, deleteFirst: true };\n }\n const previousName = olds?.name ?? output?.name;\n if (news.name !== undefined && previousName !== undefined && news.name !== previousName) {\n return { action: \"replace\" as const, deleteFirst: true };\n }\n const previousQuery = olds?.query ?? output?.query;\n if (previousQuery !== undefined && !jsonEqual(previousQuery, news.query)) {\n return { action: \"replace\" as const, deleteFirst: true };\n }\n const previousOptions = olds?.exportOptions ?? output?.exportOptions;\n if (\n news.exportOptions !== undefined &&\n previousOptions !== undefined &&\n !jsonEqual(previousOptions, news.exportOptions)\n ) {\n return { action: \"replace\" as const, deleteFirst: true };\n }\n return undefined;\n }),\n\n read: Effect.fn(function* ({ id, olds, output, previous }) {\n const env = yield* GcpEnvironment.current;\n const matterId = olds?.matterId ?? output?.matterId ?? \"\";\n const exportId = olds?.exportId ?? output?.exportId ?? \"\";\n let existing = yield* getExport(matterId, exportId);\n if (existing === undefined) {\n const ownership = yield* ownershipLabels(id);\n const name = encodeOwnershipLine(\n ownership,\n olds?.name ?? output?.name,\n MAX_EXPORT_NAME_LENGTH,\n );\n existing = yield* findExportByName(matterId, name);\n }\n if (existing === undefined) {\n existing = yield* findOwnedExport(id, matterId);\n }\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, env.project);\n return (yield* ownedByAlchemy(id, existing.name))\n ? attrs\n : unownedUnlessPrevious(attrs, previous, \"exportId\");\n }),\n\n list: () =>\n Effect.gen(function* () {\n const env = yield* GcpEnvironment.current;\n const matters = yield* listActiveMatters();\n const pages = yield* Effect.forEach(\n matters,\n (matter) =>\n listExports(matter.matterId ?? \"\").pipe(\n Effect.map((items) =>\n items\n .filter((item) => hasOwnershipMarker(item.name))\n .map((item) => toAttrs(item, env.project)),\n ),\n ),\n { concurrency: 4 },\n );\n return pages.flat();\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output }) {\n const env = yield* GcpEnvironment.current;\n const matterId = news.matterId;\n const ownership = yield* ownershipLabels(id);\n const displayName = yield* toGeneratedName(id, news.name, output?.name, 40);\n const name = encodeOwnershipLine(ownership, displayName, MAX_EXPORT_NAME_LENGTH);\n const desired: vault.Export = {\n name,\n query: news.query,\n exportOptions: news.exportOptions,\n };\n\n let current = yield* getExport(matterId, news.exportId ?? output?.exportId ?? \"\");\n if (current === undefined) {\n current = yield* findExportByName(matterId, name);\n }\n if (current === undefined) {\n current = yield* findOwnedExport(id, matterId);\n }\n\n if (current === undefined) {\n const created = yield* vault\n .createMattersExports({\n matterId,\n body: desired,\n })\n .pipe(Effect.catchTag(\"Conflict\", () => findExportByName(matterId, name)));\n current = created ?? undefined;\n }\n\n if (current === undefined) {\n return yield* new MattersExportNotResolved({\n matterId,\n exportId: news.exportId ?? output?.exportId ?? name,\n });\n }\n\n return toAttrs(current, env.project);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n if (output.matterId.length === 0 || output.exportId.length === 0) {\n return;\n }\n yield* ignoreMissing(\n vault.deleteMattersExports({\n matterId: output.matterId,\n exportId: output.exportId,\n }),\n );\n }),\n });\n","preview":null,"history":null,"version":"c0d10273381ce108e3c63ff3d3e9c849efc588c0"},"/_session?shell=1":null}