Import data into DevRevExtract records

Resume nested parent and child extraction

Reuse parent-page identities and checkpoint child pages without losing pending records.

Keep the pending parent page's IDs and child cursor in state when children are available only through /parents/{id}/children.

Provider contract

The source client must supply validated records with stable IDs and RFC3339 timestamps, bounded parent pages and cursors valid for the run's snapshot. Bind both methods to the same sync unit and extraction window. Parent selection must include parents of changed children even when the parents are unchanged.

The client throws SourceRateLimit with a parsed delay for HTTP 429 and other errors for failed requests. Apply the provider's cursor-expiry policy on an expired snapshot.

Extraction helper

Declare parents and children in the EDM, with a child parent_id reference. Child IDs are parent-scoped. This example requires both types when children are selected; supporting children-only extraction requires a separate reference-resolution design.

import type {
  ExtractionAdapter,
  NormalizedItem,
  TaskResult,
} from "@devrev/airsync-sdk";

type RecordData = {
  id: string;
  title: string;
  created_at: string;
  updated_at: string;
};
type Page = { items: RecordData[]; nextCursor: string | null };
export type Source = {
  parents(cursor: string | null): Promise<Page>;
  children(parentId: string, cursor: string | null): Promise<Page>;
};
export class SourceRateLimit extends Error {
  constructor(public readonly delaySeconds: number) {
    super("Source rate limited");
  }
}
export type State = {
  runId: string;
  parentCursor: string | null;
  pending: {
    ids: string[];
    nextCursor: string | null;
    index: number;
    childCursor: string | null;
  } | null;
  completed: boolean;
};
export function initialState(runId = ""): State {
  return { runId, parentCursor: null, pending: null, completed: false };
}
function normalized(record: RecordData, parentId?: string): NormalizedItem {
  return {
    // JSON encoding prevents collisions between composite ID components.
    id:
      parentId === undefined
        ? record.id
        : JSON.stringify([parentId, record.id]),
    created_date: record.created_at,
    modified_date: record.updated_at,
    data: {
      title: record.title,
      ...(parentId === undefined ? {} : { parent_id: parentId }),
    },
  };
}

export async function extractNested(
  adapter: ExtractionAdapter<State>,
  source: Source,
): Promise<TaskResult> {
  const runId = adapter.event.payload.event_context.run_id;
  if (adapter.state.runId !== runId) adapter.state = initialState(runId);
  const parentsSelected = adapter.shouldExtract("parents");
  const childrenSelected = adapter.shouldExtract("children");
  if (childrenSelected && !parentsSelected) {
    return {
      status: "error",
      error: { message: "Children require selected parents" },
    };
  }
  if (!parentsSelected || adapter.state.completed) return { status: "success" };

  adapter.initializeRepos([
    { itemType: "parents" },
    ...(childrenSelected ? [{ itemType: "children" }] : []),
  ]);
  const parentRepo = adapter.getRepo("parents");
  const childRepo = adapter.getRepo("children");
  if (!parentRepo || (childrenSelected && !childRepo)) {
    throw new Error("Required extraction repository is missing");
  }

  // Bound each invocation as well as observing the SDK soft timeout.
  let requests = 0;
  try {
    while (!adapter.state.completed) {
      const pending = adapter.state.pending;
      if (
        pending &&
        (!childrenSelected || pending.index === pending.ids.length)
      ) {
        adapter.state.parentCursor = pending.nextCursor;
        adapter.state.completed = pending.nextCursor === null;
        adapter.state.pending = null;
        continue;
      }
      if (adapter.isTimeout || requests >= 20) return { status: "progress" };
      requests++;
      if (!pending) {
        const page = await source.parents(adapter.state.parentCursor);
        if (
          page.nextCursor !== null &&
          page.nextCursor === adapter.state.parentCursor
        ) {
          throw new Error("Parent cursor did not advance");
        }
        await parentRepo.push(page.items.map((record) => normalized(record)));
        await parentRepo.upload();
        // Cache identities only after parent output has uploaded.
        adapter.state.pending = {
          ids: page.items.map((record) => record.id),
          nextCursor: page.nextCursor,
          index: 0,
          childCursor: null,
        };
      } else {
        const parentId = pending.ids[pending.index];
        const page = await source.children(parentId, pending.childCursor);
        if (
          page.nextCursor !== null &&
          page.nextCursor === pending.childCursor
        ) {
          throw new Error("Child cursor did not advance");
        }
        if (!childRepo) throw new Error("Children repository is missing");
        await childRepo.push(
          page.items.map((record) => normalized(record, parentId)),
        );
        await childRepo.upload();
        // Never checkpoint past a fetched-but-unuploaded child page.
        pending.childCursor = page.nextCursor;
        if (page.nextCursor === null) pending.index++;
      }
    }
    return { status: "success" };
  } catch (error) {
    if (
      error instanceof SourceRateLimit &&
      Number.isFinite(error.delaySeconds) &&
      error.delaySeconds >= 0
    ) {
      return { status: "delay", delaySeconds: error.delaySeconds };
    }
    throw error;
  }
}

Call extractNested(adapter, source) from processExtractionTask<State> and return its result. Seed spawn() with initialState(). Keep the source connection, sync unit and window unchanged on continuation; the helper resets when run_id changes.

The helper uploads each page before advancing its cursor. A crash before the SDK saves state can still replay uploaded records; see state persistence.

Verify a parent spanning multiple invocations resumes without relisting its parent page. Cover timeout, 429, failed uploads, empty pages with a next cursor, parents-only selection and a new run. A failed upload must leave its cursor unchanged.

Last updated on