Skip to content

Client RPC Functions

These functions are called by the frontend application to initiate workflows and interact with the processing pipeline. They typically validate requests, update entity status, and create processing jobs that workers will pick up automatically.

Response Format

Client RPCs use different response formats depending on their purpose:

Job Initiation Functions

Functions that create jobs return:

typescript
{
  "job_id": string | null,
  "error": string | null,
  "retry": boolean
}

Status Update Functions

Functions that update status return:

json
{
  "success": boolean,
  "error": string | null,
  "retry": boolean
}

Common Pattern

Client RPCs typically follow this workflow:

  1. Authenticate - Verify user is logged in
  2. Validate - Check entity exists and is in correct state
  3. Update Status - Change entity status to indicate workflow is starting
  4. Create Job - Insert job into processing.processing_jobs with queued status
  5. Return - Provide job ID or success confirmation

Workers automatically pick up queued jobs and progress through the pipeline.

Exception Handling

Like worker functions, client RPCs have comprehensive exception handling:

sql
EXCEPTION
    WHEN deadlock_detected THEN
        RETURN jsonb_build_object('job_id', NULL, 'error', '...', 'retry', true);

    WHEN OTHERS THEN
        RETURN jsonb_build_object('job_id', NULL, 'error', SQLERRM || ' (SQLSTATE: ' || SQLSTATE || ')', 'retry', false);

Function Reference

request_shareholder_research

Summary: Initiates shareholder research for a specific entity.

Context: Triggered when a user clicks the button to request shareholder information for a company. Validates that research hasn't already started, updates the entity status, and creates a download job. This begins a two-stage workflow: download the shareholder document, then parse it with LLM.

Signature:

sql
request_shareholder_research(p_entity_id UUID) RETURNS JSONB

Parameters:

NameTypeRequiredDescription
p_entity_idUUIDYesThe ID of the entity to research shareholders for

Core Logic & Behavior:

  1. Entity Validation:

    • Checks entity exists by querying shareholder_research_status
    • Returns error if entity not found
    • Validates current status is not_started
    • Returns error if research already initiated
  2. Status Update:

    • Sets shareholder_research_status to ready
    • Updates updated_at timestamp
  3. Job Creation:

    • Creates new processing_jobs entry
    • Sets type to shareholder_download
    • Sets status to queued
    • Links to entity via entity_id

Return Value:

Success:

json
{
  "job_id": "uuid-of-created-job",
  "error": null,
  "retry": false
}

Entity not found:

json
{
  "job_id": null,
  "error": "Entity with id ... does not exist",
  "retry": false
}

Already initiated:

json
{
  "job_id": null,
  "error": "Shareholder research already initiated for entity. Current status: downloading",
  "retry": false
}

Workflow Initiated:

This starts a two-stage automated process:

  1. Download Stage:

    • Worker picks up shareholder_download job
    • Downloads shareholder list from Handelsregister
    • Stores file via record_file_and_document
    • Calls store_shareholder_download_results
    • Automatically creates parsing job
  2. Parsing Stage:

    • Worker picks up shareholder_parsing job
    • Extracts data via LLM
    • Calls store_shareholder_parsing_results
    • Marks research as complete

Permissions: Uses SECURITY DEFINER. Intended for authenticated frontend users.

Frontend Usage:

typescript
const { data } = await supabase.rpc('request_shareholder_research', {
  p_entity_id: entityId
});

if (data.job_id) {
  // Poll job status or subscribe to job updates
  watchJobProgress(data.job_id);
}

start_entity_basic_discovery

Summary: Initiates the basic discovery process for an entity by updating its status from 'discovered' to 'basic_discovery_running'.

Context: Part of Path B in the technical flow, where users manually select specific entities from a list of 4-20 discovered results. After selecting which entities to process, this function updates the status to trigger the next processing phase.

Signature:

sql
start_entity_basic_discovery(entity_id uuid) RETURNS json

Parameters:

NameTypeRequiredDescription
entity_iduuidYesThe unique identifier of the entity to start basic discovery for

Core Logic & Behavior:

  1. Authentication Check:

    • Verifies user is authenticated via auth.uid()
    • Returns error if not authenticated
  2. Entity Validation:

    • Checks entity exists in content.entities
    • Validates current processing_status is discovered
    • Returns specific error for not found or invalid status
  3. Status Update:

    • Updates processing_status to basic_discovery_running
    • Sets updated_at to current timestamp
    • Uses conditional WHERE clause to prevent race conditions

Return Value:

Success:

json
{
  "success": true
}

Not authenticated:

json
{
  "success": false,
  "error": "Authentication required"
}

Invalid status:

json
{
  "success": false,
  "error": "Entity status is not 'discovered'"
}

Permissions: Uses SECURITY DEFINER. Requires user authentication.

Frontend Usage:

typescript
const { data } = await supabase.rpc('start_entity_basic_discovery', {
  entity_id: entityId
});

if (data.success) {
  // Entity is now processing - update UI
  refreshEntityList();
}

start_deep_research

Summary: Initiates the deep research process for an entity by updating its status and creating a document collection job.

Context: Called when a user wants to perform deep research on an entity that has completed basic discovery. This transitions the entity from basic_discovery_complete to deep_research_ready and creates a job to collect all available documents from the Handelsregister.

Signature:

sql
start_deep_research(entity_id UUID) RETURNS jsonb

Parameters:

NameTypeRequiredDescription
entity_idUUIDYesThe unique identifier of the entity to start deep research for

Core Logic & Behavior:

  1. Authentication Check:

    • Verifies user is authenticated
    • Returns error if not authenticated
  2. Entity Validation:

    • Checks entity exists
    • Validates processing_status is basic_discovery_complete
    • Returns error if in wrong state
  3. Status Update:

    • Sets processing_status to deep_research_ready
    • Updates updated_at timestamp
  4. Job Creation:

    • Creates processing_jobs entry
    • Sets type to collection (document collection job)
    • Sets status to queued
    • Links to entity

Return Value:

Success:

json
{
  "success": true
}

Not authenticated:

json
{
  "success": false,
  "error": "Authentication required"
}

Invalid status:

json
{
  "success": false,
  "error": "Basic discovery not complete"
}

Processing Pipeline:

This initiates the deep research workflow:

  1. Collection Stage: Worker downloads all available documents
  2. OCR Stage: Processes scanned documents
  3. Chunking Stage: Splits documents for LLM processing
  4. Analysis Stage: Extracts structured information

Permissions: Uses SECURITY DEFINER. Requires user authentication.

Frontend Usage:

typescript
const { data } = await supabase.rpc('start_deep_research', {
  entity_id: entityId
});

if (data.success) {
  // Show processing indicator
  showDeepResearchProgress(entityId);
}

Notes:

  • Only works on entities with status basic_discovery_complete
  • Part of the processing pipeline: basic_discovery_complete → deep_research_ready → deep_research_running → ... → complete
  • Workers automatically update status as they progress through stages