File size: 3,706 Bytes
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
68697dc
 
74888a1
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
 
 
 
 
68697dc
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""
Optional Supabase run tracker.

Tracks pipeline runs in a Supabase `runs` table for persistent history across sessions.
All methods are silent no-ops when SUPABASE_URL / SUPABASE_KEY are not set.

Required Supabase schema (run once in SQL editor):

    create table runs (
      id uuid primary key default gen_random_uuid(),
      pipeline text not null,
      source_file text,
      status text default 'running',
      total_items int,
      completed_items int default 0,
      results_sheet_url text,
      cost_usd numeric(10,4),
      started_at timestamptz default now(),
      completed_at timestamptz,
      metadata jsonb
    );
"""

import os
from typing import Optional
from loguru import logger


def _get_client():
    """Return a Supabase client if credentials are configured, else None."""
    url = os.getenv("SUPABASE_URL")
    key = os.getenv("SUPABASE_KEY")
    if not url or not key:
        return None
    try:
        from supabase import create_client

        return create_client(url, key)
    except ImportError:
        logger.warning(
            "supabase package not installed. Run: pip install supabase>=2.0.0"
        )
        return None
    except Exception as e:
        logger.warning(f"Could not connect to Supabase: {e}")
        return None


class RunTracker:
    """
    Tracks a single pipeline run in Supabase.

    Usage:
        tracker = RunTracker("ip_check", source_file="comic.pdf")
        tracker.start(total_items=62)
        tracker.update(10)
        tracker.finish("completed", results_sheet_url="https://...", cost_usd=4.20)
    """

    def __init__(self, pipeline: str, source_file: str = None):
        self._client = _get_client()
        self._run_id: Optional[str] = None
        self.pipeline = pipeline
        self.source_file = source_file

    def start(self, total_items: int) -> Optional[str]:
        """Insert a new run record. Returns run_id or None."""
        if not self._client:
            return None
        try:
            res = (
                self._client.table("runs")
                .insert(
                    {
                        "pipeline": self.pipeline,
                        "source_file": self.source_file,
                        "total_items": total_items,
                        "status": "running",
                    }
                )
                .execute()
            )
            self._run_id = res.data[0]["id"]
            logger.info(f"Supabase run started: {self._run_id}")
            return self._run_id
        except Exception as e:
            logger.warning(f"Supabase run tracking unavailable: {e}")
            return None

    def update(self, completed: int, **extra):
        """Update completed_items and any extra fields."""
        if not self._client or not self._run_id:
            return
        try:
            self._client.table("runs").update(
                {"completed_items": completed, **extra}
            ).eq("id", self._run_id).execute()
        except Exception:
            pass

    def finish(self, status: str = "completed", **extra):
        """Mark run as finished with final status and any extra fields."""
        if not self._client or not self._run_id:
            return
        try:
            from datetime import datetime, timezone

            self._client.table("runs").update(
                {
                    "status": status,
                    "completed_at": datetime.now(timezone.utc).isoformat(),
                    **extra,
                }
            ).eq("id", self._run_id).execute()
            logger.info(f"Supabase run finished: {self._run_id} [{status}]")
        except Exception:
            pass