Skip to the page

Guides · App patterns

Files, media & document search

Upload verified files straight to object storage, extract PDF pages in background jobs and run hybrid passage search with cited links under workspace rules.

What you’ll build#

You will build a workspace document and media library where teammates upload PDFs, images and MP4 video directly to object storage, extract PDF pages into indexed passages in the background and search across documents with cited page links. Workspace membership and guest shares govern every layer, so unsharing a document revokes both the file link and every passage match in a single atomic commit.

Caller-scoped PDF passage extraction

Completing a magic-byte-verified PDF upload queues an ext::napalm::Job that reads file_url as the uploader and upserts page-level Passage rows.

Policy-inherited hybrid RRF search

ext::ai::hybrid_search fuses vector similarity and fts::index keyword rank while evaluating .document.is_readable during candidate scoring.

Direct object uploads
Bytes stream straight between clients and object storage, and Napalm checks byte length and magic-byte signatures before marking a Document row Ready.
Caller-scoped ingestion
An ext::napalm::Job runs as the uploading caller, reads file_url inside an action handler and writes page-level Passage rows in idempotent batches.
Hybrid passage search
Callers reach embeddings through each Passage record under workspace rules. One query fuses ext::ai::index meaning and fts::index keyword rank.
Cached presigned links
The Document record decides who receives a link, and window-aligned presigned URLs let browsers and CDNs cache authorized files across repeated searches.

You need a project with sign-in configured, file buckets and search storage enabled on the cluster and a model provider configured for embeddings. Your first app sets up a starter project.

Terminal
napalm storage enable acme-cluster files --label notesnapalm storage enable acme-cluster searchnapalm models notes --give

Model documents and indexed passages#

Extend ext::files::File on Document so metadata, workspace links and access rules live in PostgreSQL while raw file bytes stay in object storage. Overloading file_size with constraint max_value caps upload byte counts at mutation time, and overloading file_format with constraint one_of restricts accepted binary headers once POST /uploads/complete sniffs the stored object. Because file_format starts empty when an upload opens, the insert succeeds before any bytes land.

Each Passage row stores one extracted PDF page linked to a parent Document. An exclusive constraint on (.document, .page_number) prevents duplicate pages, while a deferred ext::ai::index and an fts::index index the page text. Embeddings are not stored on the record. Callers reach embeddings through each Passage record under that record’s access policies.

dbschema/default.gel
using extension auth;using extension files;using extension ai;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;   abstract type NapalmTextEmbedding3Small extending ext::ai::EmbeddingModel {    annotation ext::ai::model_name := 'openai/text-embedding-3-small';    annotation ext::ai::model_provider := 'napalm';    annotation ext::ai::embedding_model_max_input_tokens := '8191';    annotation ext::ai::embedding_model_max_batch_tokens := '8191';    annotation ext::ai::embedding_model_max_output_dimensions := '1536';    annotation ext::ai::embedding_model_supports_shortening := 'true';  }   scalar type ExtractionStatus extending enum<Pending, Queued, Indexed>;   type Workspace {    required name: str;    multi members: ext::auth::Identity;    access policy member_can_read allow select using ((global caller in .members) ?? false);    access policy member_can_write allow insert, update, delete using ((global caller in .members) ?? false);  }   type Document extending ext::files::File {    required workspace: Workspace { readonly := true; on target delete delete source; };    required uploaded_by: ext::auth::Identity;    multi shared_with: ext::auth::Identity;    required title: str;    page_count: int32;    required extraction_status: ExtractionStatus { default := ExtractionStatus.Pending; };     overloaded file_size: int64 {      constraint max_value(524288000) { errmessage := 'files must be 500 MiB or smaller'; };    };    overloaded file_format: ext::files::Format {      constraint one_of(        ext::files::Format.Pdf, ext::files::Format.Png, ext::files::Format.Jpeg,        ext::files::Format.Webp, ext::files::Format.Mp4      ) { errmessage := 'upload a PDF, PNG, JPEG, WebP or MP4 file'; };    };     # Single-sourced access predicates shared with Passage.    is_readable := (((global caller in .workspace.members) ?? false) or ((global caller in .shared_with) ?? false));    is_writable := ((global caller in .workspace.members) ?? false);     access policy readers_can_select allow select using (.is_readable);    access policy members_can_write allow insert, update, delete using (.is_writable);  }   type Passage {    required document: Document { readonly := true; on target delete delete source; };    required page_number: int32 { constraint min_value(1); };    required text: str;    constraint exclusive on ((.document, .page_number));     deferred index ext::ai::index(embedding_model := 'openai/text-embedding-3-small') on (.text);    index fts::index on (fts::with_options(.text, language := fts::Language.eng));     access policy document_readers_can_select allow select using (.document.is_readable);    access policy document_writers_can_modify allow insert, update, delete using (.document.is_writable);  }}

Upload large files with progress and recovery#

Setting file_size on an insert or on an update of a non-Ready row opens a write-once upload session and returns a file_upload descriptor once in that mutation’s response. Any later select returns null for file_upload. Once a file reaches Ready, stored bytes are immutable so cited pages and backups never change after verification.

File metadata record

Inserting Document with file_size creates the ext::files::File record in PostgreSQL and returns a one-time file_upload plan.

Direct-to-bucket byte stream

napalm.upload streams SHA-256-verified chunks straight from the client into the dedicated object bucket with resumable part tracking.

Magic-byte verification seal

POST /uploads/complete sniffs stored magic bytes against your file_format constraint before stamping Ready or rejecting disguised files.

dbschema/queries/createDocument.edgeql
# Open a direct upload session, or call update on a non-Ready row when an upload expiresselect (insert Document {  workspace := (select Workspace filter .id = <uuid>$workspace),  uploaded_by := assert_exists(global caller),  title := <str>$title,  file_name := <str>$file_name,  file_size := <int64>$file_size,}) { id, file_status, file_upload }
dbschema/queries/workspaceDocuments.edgeql
select Document {  id, title, file_name, file_size, file_status, file_format,  file_error, file_url, file_download_url, page_count, extraction_status,}filter .workspace.id = <uuid>$workspaceorder by .title

Pass the returned descriptor to napalm.upload(file_upload, file, { onProgress }) from napalm-client. Small files upload in one presigned PUT with If-None-Match: *. Large files hash 16 parts per window with Web Crypto SHA-256, request presigned part URLs from POST /uploads/parts (up to 1,000 parts per call), stream four parts at a time directly to object storage and finalize at POST /uploads/complete. Subscribing to workspaceDocuments with useLiveQuery updates each row from Uploading to Ready and Indexed without polling.

components/DocumentLibrary.tsx
// components/DocumentLibrary.tsximport { deployed, NapalmError, type FileUpload } from 'napalm-client'import { useLiveQuery, useNapalm } from 'napalm-client/react'import { useRef, useState } from 'react' type DocumentRow = {  id: string; title: string; file_status: 'Empty' | 'Uploading' | 'Ready'  file_format: string | null; file_error: string | null; file_url: string | null  extraction_status: 'Pending' | 'Queued' | 'Indexed'}const workspaceDocuments = deployed<DocumentRow, { workspace: string }>('workspaceDocuments') export function DocumentLibrary({ workspaceId }: { workspaceId: string }) {  const napalm = useNapalm()  const { rows } = useLiveQuery(workspaceDocuments, { workspace: workspaceId })  const [progress, setProgress] = useState<number | null>(null)  const [message, setMessage] = useState('')  const pendingUploads = useRef(new Map<string, { documentId: string; plan: FileUpload }>())   async function call<Row>(name: string, variables: Record<string, unknown>): Promise<Row[]> {    const res = await napalm.fetch(`https://notes.napalmdata.com/query/${name}`, {      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ variables }),    })    const body = await res.json()    if (!res.ok) throw NapalmError.fromJson(body, res.status)    return body.data  }   async function uploadFile(file: File) {    const cacheKey = `${workspaceId}:${file.name}:${file.size}`    setMessage('')    setProgress(0)    let saved = pendingUploads.current.get(cacheKey)    if (!saved) {      const [created] = await call<{ id: string; file_upload: FileUpload }>('createDocument', {        workspace: workspaceId, title: file.name.replace(/\.[^.]+$/, ''), file_name: file.name, file_size: file.size,      })      saved = { documentId: created.id, plan: created.file_upload }      pendingUploads.current.set(cacheKey, saved)    }    try {      const facts = await napalm.upload(saved.plan, file, { onProgress: (sent, total) => setProgress(sent / total) })      pendingUploads.current.delete(cacheKey)      setProgress(null)      if (facts.format === 'Pdf') await call('queueDocumentExtraction', { document: saved.documentId })    } catch (err) {      setProgress(null)      if (err instanceof NapalmError && err.code === 'expired_upload') pendingUploads.current.delete(cacheKey)      setMessage(err instanceof Error ? err.message : 'Upload failed.')    }  }   return (    <section>      <input type="file" onChange={(e) => e.target.files?.[0] && void uploadFile(e.target.files[0])} />      {progress !== null && <p>Uploading: {Math.round(progress * 100)}%</p>}      {message && <p role="alert">{message}</p>}      <ul>        {rows?.map((doc) => (          <li key={doc.id}>            <strong>{doc.title}</strong> ({doc.file_status}{doc.file_format === 'Pdf' ? ` · ${doc.extraction_status}` : ''})            {doc.file_error && <span> · Refused: {doc.file_error}</span>}            {doc.file_url && <a href={doc.file_url}>Open</a>}          </li>        ))}      </ul>    </section>  )}
Error codefile_errorCause and recovery
size_mismatchSizeMismatchCause and recoveryStored byte length differed from file_size. Napalm deletes the rejected object. Open a fresh upload with the current byte count.
type_mismatchTypeMismatchCause and recoverySniffed magic bytes on a public file contradicted the declared media type. Re-upload matching bytes or omit a mismatched header.
not_acceptedNotAcceptedCause and recoverySniffed file_format failed your schema’s one_of constraint (for example an SVG or ZIP renamed .pdf). Show err.message in the UI.
parts_incomplete—Cause and recoveryNetwork dropped before every multipart chunk arrived. Keep file_upload and call napalm.upload again to skip parts already stored.
expired_uploadExpiredCause and recoveryUpload token aged past expiry and file_status reset to Empty. Update file_size on the row to obtain a fresh file_upload plan.

See File uploads for the wire payloads of POST /uploads/parts and POST /uploads/complete.

Extract passages when an upload finishes#

Once napalm.upload resolves with facts.format === 'Pdf', queue background extraction by updating extraction_status to Queued and inserting an ext::napalm::Job in the same statement. Non-PDF uploads (Png, Jpeg, Webp and Mp4) skip this mutation and serve immediately through file_url.

  1. Write the outbox mutation, gatekeeper query and batch upsert

    queueDocumentExtraction transitions Pending to Queued once, so duplicate calls queue no extra job. When the job runs, extractDocumentPassages executes as the queuing caller. If the caller lost workspace access or an earlier attempt already marked the document Indexed, the query returns zero rows and the job completes without calling your handler.

    dbschema/queries/queueDocumentExtraction.edgeql
    # Mark a verified PDF queued and insert the extraction job in one transactionwith  ready_doc := (    update Document filter .id = <uuid>$document and <str>.file_status = 'Ready'      and <str>.file_format = 'Pdf' and .extraction_status = ExtractionStatus.Pending    set { extraction_status := ExtractionStatus.Queued }  ),  queued := (    for doc in ready_doc union (      insert ext::napalm::Job { query := 'extractDocumentPassages', variables := <json>(document := <str>doc.id) }    )  ),select ready_doc { id, extraction_status }
    dbschema/queries/extractDocumentPassages.edgeql
    # Action gatekeeper: runs as the queuing caller and skips documents already indexedselect Document { id, title }filter .id = <uuid>$document and <str>.file_status = 'Ready'  and <str>.file_format = 'Pdf' and .extraction_status = ExtractionStatus.Queued
    dbschema/queries/readDocumentUrl.edgeql
    select Document { file_url }filter .id = <uuid>$document and <str>.file_status = 'Ready'
    dbschema/queries/saveDocumentPassages.edgeql
    # Upsert a page batch and flip extraction_status when the final batch commitswith  doc := assert_single((    update Document filter .id = <uuid>$document set {      page_count := <optional int32>$page_count ?? .page_count,      extraction_status := (ExtractionStatus.Indexed if exists <optional int32>$page_count else .extraction_status),    }  )),  saved := (    for page in json_array_unpack(<json>$pages) union (      insert Passage { document := doc, page_number := <int32>page['page_number'], text := <str>page['text'] }      unless conflict on ((.document, .page_number)) else (update Passage set { text := <str>page['text'] })    )  ),select { count := count(saved) }
  2. Read file_url and write page batches as the caller

    Inside handleCalls, await call.db() trades the signed call assertion for a 60-second NapalmClient bound to the queuing caller. Query readDocumentUrl through that client, split extracted pages into batches under the 1 MiB statement body limit and pass page_count on the final batch so saveDocumentPassages flips extraction_status to Indexed. Each job attempt has 120 seconds for the gatekeeper query and handler combined.

    app/actions/[action]/route.ts
    // app/actions/[action]/route.tsimport { handleCalls } from 'napalm-client'import { extractPdfPages } from '@/lib/pdf' const PAGES_PER_BATCH = 50 export const POST = handleCalls(  {    async extractDocumentPassages(call) {      const [queued] = call.rows as { id: string; title: string }[]      const callerDb = await call.db()       // Read file_url under the caller's 60-second exchanged session.      const sourceRes = await callerDb.fetch('https://notes.napalmdata.com/query/readDocumentUrl', {        method: 'POST', headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ variables: { document: queued.id } }),      })      const { data } = (await sourceRes.json()) as { data?: { file_url: string | null }[] }      const pdfUrl = data?.[0]?.file_url      if (!sourceRes.ok || !pdfUrl) throw new Error('Document URL unavailable for caller.')       const pdfBytes = await fetch(pdfUrl).then((r) => r.arrayBuffer())      const pages = await extractPdfPages(pdfBytes, { idempotencyKey: call.job?.id ?? queued.id })       for (let i = 0; i < pages.length; i += PAGES_PER_BATCH) {        const isLast = i + PAGES_PER_BATCH >= pages.length        const saved = await callerDb.fetch('https://notes.napalmdata.com/query/saveDocumentPassages', {          method: 'POST', headers: { 'Content-Type': 'application/json' },          body: JSON.stringify({            variables: { document: queued.id, pages: pages.slice(i, i + PAGES_PER_BATCH), page_count: isLast ? pages.length : null },          }),        })        if (!saved.ok) throw new Error(`Passage batch failed: ${saved.status}`)      }      return { documentId: queued.id, pagesIndexed: pages.length }    },  },  { address: 'https://notes.napalmdata.com', handlers: 'https://api.example.com/actions', secret: process.env.NAPALM_ACTION_SECRET },)
    Idempotent retries
    call.job.id stays constant across every retry attempt of a job. Pass call.job.id to external OCR services, and rely on unless conflict on ((.document, .page_number)) so retried page batches overwrite cleanly.
    Immediate keyword recall
    Committed Passage rows match fts::index immediately while Napalm computes vector embeddings in the background.
  3. Deploy the queries and attach the handler

    Terminal
    napalm queries push notesnapalm actions add notes extractDocumentPassages \  https://api.example.com/actions/extractDocumentPassages --timeout 30napalm generate notes --deployed --lang ts

    You can also place the handler in handlers/extractDocumentPassages.ts and run napalm handlers deploy notes instead of hosting an external HTTPS route. See Hosted handlers and Actions & background jobs.

Hybrid search fuses semantic similarity from ext::ai::index with keyword ranking from fts::index via Reciprocal Rank Fusion, so conceptual questions and exact contract clauses rank in one pass. Napalm evaluates .document.is_readable during candidate scoring rather than filtering a global top-k afterward. Every caller receives a full page of permitted citations.

Deploy searchPassages to return ranked snippets alongside parent Document fields and presigned URLs in a single round trip. Appending #page={hit.page_number} to file_url opens browser PDF viewers directly at the cited page. External agents on /mcp and clients calling napalm.search('Passage', query) can also query POST /search under the same access rules.

dbschema/queries/searchPassages.edgeql
# Hybrid RRF search returning cited passages and window-aligned file linkswith hits := (  select ext::ai::hybrid_search(Passage, <str>$query, language := 'eng')  filter .object.document.workspace.id = <uuid>$workspace  order by .score desc limit <int64>$limit)select (  for hit in hits union {    id := hit.object.id, score := hit.score, page_number := hit.object.page_number, text := hit.object.text,    document := hit.object.document { id, title, file_name, file_url, file_download_url },  })order by .score desc
POST /search
{  "type": "Passage",  "query": "indemnification cap for enterprise renewals",  "fields": ["page_number", "text"],  "limit": 8}

Private file_url and file_download_url links are signed once in each 1-hour window and remain valid for 6 hours. Every search within the same window produces the identical URL string for a document, so browser tabs and CDN edges serve cached PDFs instead of re-fetching bytes on every citation click.

Window-aligned presigned links & policy gate

Permitted reads within the same signing window receive an identical presigned file_url for browser and edge caching, while unsharing a Document withholds links on the very next commit.

dbschema/queries/unshareDocument.edgeql
# Remove a guest viewer to revoke file_url and every Passage hit in the same commitupdate Document filter .id = <uuid>$documentset { shared_with -= (select .shared_with filter .id = <uuid>$viewer) }
Same-commit unshare
Removing a guest from Document.shared_with or removing a member from Workspace.members flips .is_readable in that commit. Subsequent searches, live queries and Document selects withhold both passages and file_url immediately.
Cascading deletes
on target delete delete source on Passage.document drops every passage and index entry when a Document is deleted, and object storage retains the immutable bytes until the backup retention window expires.

Check uploads and passage search#

Terminal
napalm files status notesnapalm files errors notes default::Documentnapalm queue ls notes --query extractDocumentPassagesnapalm people reach notes guest@example.comnapalm explain-access notes 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --as guest@example.com
  1. Reject a disguised file by magic bytes

    Rename a ZIP archive to handbook.pdf and upload the file. POST /uploads/complete sniffs the archive header, rejects the upload with 409 not_accepted, deletes the stored bytes and records NotAccepted in napalm files errors notes default::Document.

  2. Upload a multi-page PDF and follow extraction

    Upload a valid PDF in your app. The live list transitions from Uploading to Ready, napalm queue ls notes --query extractDocumentPassages shows the job reach completed and the document row records page_count and marks extraction_status as Indexed.

  3. Query both exact clauses and conceptual paraphrases

    Search for an exact phrase from one page and then a conceptual paraphrase of another page. Confirm both queries return ranked Passage snippets with page_number and a working document.file_url.

  4. Unshare a guest viewer and confirm revocation

    Run unshareDocument for a guest viewer, then inspect napalm people reach notes guest@example.com and napalm explain-access on the document UUID. Confirm the guest’s Document and Passage counts drop and re-running the search as that guest returns zero hits.

Next steps#

In-app AI copilots
Pair cited passage retrieval with POST /ask and dry-run mutation proposals under user sessions and expiring AgentGrant tokens.
React Native
Stream resumable camera and disk uploads from iOS and Android using fileSource and hardware SHA-256.
Datasets & ML training
Export workspace-consented rows into immutable Parquet ext::files::File shards for model fine-tuning.
Files & object storage
Configure public buckets, custom CNAME asset domains and zero-downtime imports from external S3 buckets.

Type a word or two to search every docs page.