Contenus volumineux

Copier un collecteur borné, adapter l’enveloppe et vérifier le contenu avant de le lire.

Rédigé par Red Blue

Mis à jour le

Certaines lectures renvoient un document en plusieurs réponses. Le collecteur ci-dessous assemble les fragments, borne le volume et le nombre d’appels, vérifie la cohérence et l’empreinte SHA-256 avant de parser le JSON. Il utilise les API Web standard et ne demande aucun package Khony publié sur npm.

  1. Copier le collecteur TypeScript

    Enregistrez le code de cette page dans khony-fragments.ts dans votre application serveur. Utilisez un environnement qui fournit fetch, TextEncoder, TextDecoder, crypto.subtle et atob. Ce code ne contient pas de clé et n’appelle aucune route à lui seul.

  2. Adapter la lecture à l’enveloppe du domaine

    collectJsonFragments attend jsonFragment, sha256, totalBytes et nextFragmentCursor. Pour Workflows, ces champs sont au premier niveau ; pour Roadmap, ils sont dans data. Le chargeur conserve l’identité, le produit, la requête métier et la page pendant toutes les continuations. Les autres enveloppes, notamment Status et Knowledge, ont leur propre schéma : ne les forcez pas dans cet adaptateur.

  3. Terminer le document, puis la liste métier

    Quand le document est reconstruit, examinez sa pagination interne. Pour une nouvelle page métier, recommencez un nouveau collecteur sans reprendre le curseur de fragments de la page précédente. En cas de conflit ou d’empreinte différente, abandonnez cette reconstruction et recommencez une lecture complète autorisée.

Exemple : lire un brouillon de workflow

TypeScript
import { collectJsonFragments } from "./khony-fragments";

const origin = process.env.KHONY_ORIGIN!;
const token = process.env.KHONY_ACCESS_TOKEN!;
const productId = process.env.KHONY_PRODUCT_ID!;
const draftId = process.env.KHONY_DRAFT_ID!;
const controller = new AbortController();
const draft = await collectJsonFragments(async (fragmentCursor) => {
  const response = await fetch(origin + "/api/v1/workflows/read", {
    method: "POST",
    headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" },
    signal: controller.signal,
    body: JSON.stringify({ productId, request: { kind: "draft", draftId },
      ...(fragmentCursor ? { fragmentCursor } : {}) })
  });
  if (!response.ok) throw new Error("Lecture refusée : HTTP " + response.status);
  return response.json();
}, { maxBytes: 4 * 1024 * 1024, maxFragments: 1024, signal: controller.signal });
console.log(draft);
TypeScript

Collecteurs JSON et base64

TypeScript
export type JsonFragment = {
  jsonFragment: string
  sha256: string
  totalBytes: number
  nextFragmentCursor: string | null
}
export type Base64JsonFragment = {
  base64: string
  sha256: string
  totalBytes: number
  nextOffset: number | null
}
type Bounds = { maxBytes?: number; maxFragments?: number; signal?: AbortSignal }

async function verifyJson<T>(
  bytes: Uint8Array<ArrayBuffer>,
  sha256: string
): Promise<T> {
  const actual = Array.from(
    new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)),
    (b) => b.toString(16).padStart(2, "0")
  ).join("")
  if (actual !== sha256) throw new Error("Content checksum mismatch")
  return JSON.parse(
    new TextDecoder("utf-8", { fatal: true }).decode(bytes)
  ) as T
}
function bounds(options: Bounds) {
  const maxBytes = options.maxBytes ?? 4 * 1024 * 1024
  const maxFragments = options.maxFragments ?? 1024
  if (
    !Number.isSafeInteger(maxBytes) ||
    maxBytes < 1 ||
    !Number.isSafeInteger(maxFragments) ||
    maxFragments < 1
  )
    throw new Error("Invalid reconstruction bounds")
  return { maxBytes, maxFragments }
}
function manifest(
  fragment: { totalBytes: number; sha256: string },
  maxBytes: number
) {
  if (
    !Number.isSafeInteger(fragment.totalBytes) ||
    fragment.totalBytes < 1 ||
    fragment.totalBytes > maxBytes ||
    !/^[a-f0-9]{64}$/.test(fragment.sha256)
  )
    throw new Error("Invalid or oversized content manifest")
}

/** Keep query, page and identity unchanged. Retry a conflict by starting a new read. */
export async function collectJsonFragments<T = unknown>(
  load: (cursor?: string) => Promise<JsonFragment>,
  options: Bounds = {}
): Promise<T> {
  const { maxBytes, maxFragments } = bounds(options)
  const seen = new Set<string>()
  let cursor: string | undefined,
    text = "",
    expected: JsonFragment | undefined
  for (let count = 0; count < maxFragments; count++) {
    options.signal?.throwIfAborted()
    const page = await load(cursor)
    options.signal?.throwIfAborted()
    manifest(page, maxBytes)
    expected ??= page
    if (
      page.sha256 !== expected.sha256 ||
      page.totalBytes !== expected.totalBytes
    )
      throw new Error("Content snapshot changed")
    text += page.jsonFragment
    if (text.length > maxBytes * 2)
      throw new Error("Content exceeds reconstruction bounds")
    if (page.nextFragmentCursor === null) {
      const bytes = new TextEncoder().encode(text)
      if (bytes.length !== expected.totalBytes)
        throw new Error("Incomplete content")
      return verifyJson<T>(bytes, expected.sha256)
    }
    if (!page.nextFragmentCursor || seen.has(page.nextFragmentCursor))
      throw new Error("Content continuation did not progress")
    seen.add(page.nextFragmentCursor)
    cursor = page.nextFragmentCursor
  }
  throw new Error("Content exceeds fragment limit")
}

/** Decode each base64 fragment separately; offsets count bytes, not JS characters. */
export async function collectBase64JsonFragments<T = unknown>(
  load: (offset: number) => Promise<Base64JsonFragment>,
  options: Bounds = {}
): Promise<T> {
  const { maxBytes, maxFragments } = bounds(options)
  let offset = 0,
    output: Uint8Array<ArrayBuffer> | undefined,
    expected: Base64JsonFragment | undefined
  for (let count = 0; count < maxFragments; count++) {
    options.signal?.throwIfAborted()
    const page = await load(offset)
    options.signal?.throwIfAborted()
    manifest(page, maxBytes)
    expected ??= page
    if (
      page.sha256 !== expected.sha256 ||
      page.totalBytes !== expected.totalBytes
    )
      throw new Error("Content snapshot changed")
    output ??= new Uint8Array(expected.totalBytes)
    if (page.base64.length > Math.ceil(maxBytes / 3) * 4 + 4)
      throw new Error("Content exceeds reconstruction bounds")
    const bytes = Uint8Array.from(atob(page.base64), (character) =>
      character.charCodeAt(0)
    )
    if (!bytes.length || offset + bytes.length > output.length)
      throw new Error("Invalid content offset")
    output.set(bytes, offset)
    offset += bytes.length
    if (page.nextOffset === null) {
      if (offset !== output.length) throw new Error("Incomplete content")
      return verifyJson<T>(output, expected.sha256)
    }
    if (page.nextOffset !== offset)
      throw new Error("Content continuation did not progress")
  }
  throw new Error("Content exceeds fragment limit")
}
TypeScript

Adapter un transfert Analytics

collectBase64JsonFragments attend un chargeur qui retourne base64, sha256, totalBytes et nextOffset. Dans un transfert de définition Analytics, construisez request.fragment avec expectedSha256 et l’offset en octets demandé par la fiche analytics_export_read. Décodez chaque base64 séparément ; l’offset n’est ni un index de chaîne ni une page. Le collecteur vérifie le manifeste et refuse une continuation sans progression.