Spaces:
Paused

File size: 3,944 Bytes
3808f98
 
 
 
 
 
 
 
 
 
 
091ca1d
3808f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
3808f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
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
119
120
121
122
123
124
125
126
127
"""
Core Sync — SQLModel Tables
=============================

SyncOperation: a queued mutation from an offline or delayed client.
ConflictRecord: when server and client diverge, both versions are stored
                for user-driven resolution.

Multi-tenancy: tenant_id on every row (Commandment #3)
"""

from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, Optional
from uuid import UUID, uuid4

from sqlalchemy import Column, JSON, Text
from sqlmodel import Field, SQLModel


class SyncOpStatus(str, Enum):
    PENDING = "pending"
    APPLIED = "applied"
    REJECTED = "rejected"
    CONFLICT = "conflict"


class SyncOpMethod(str, Enum):
    POST = "POST"
    PATCH = "PATCH"
    PUT = "PUT"
    DELETE = "DELETE"


class ConflictResolutionStrategy(str, Enum):
    CLIENT_WINS = "client_wins"
    SERVER_WINS = "server_wins"
    MERGE = "merge"
    MANUAL = "manual"


class SyncOperation(SQLModel, table=True):
    """
    A single queued mutation from an offline client.

    The client sends these in a batch via POST /api/v1/sync/push.
    Each operation targets a specific API path with a payload.
    """

    __tablename__ = "sync_operations"

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    tenant_id: UUID = Field(nullable=False, index=True)
    user_id: Optional[UUID] = Field(default=None, index=True)
    device_id: Optional[str] = Field(default=None, max_length=100)

    # What was the client trying to do?
    method: SyncOpMethod = Field(nullable=False)
    path: str = Field(max_length=500, nullable=False)
    payload: Dict[str, Any] = Field(
        default_factory=dict, sa_column=Column(JSON)
    )

    # Version tracking for conflict detection
    base_version: Optional[int] = Field(
        default=None,
        description="Entity version the client based its edit on",
    )
    client_ts: datetime = Field(
        nullable=False,
        description="Timestamp on the client when the mutation was created",
    )

    # Server processing
    status: SyncOpStatus = Field(
        default=SyncOpStatus.PENDING, index=True,
    )
    server_version: Optional[int] = Field(
        default=None,
        description="Resulting entity version after apply",
    )
    error: Optional[str] = Field(default=None, sa_column=Column(Text))

    # Metadata
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False)
    processed_at: Optional[datetime] = Field(default=None)


class ConflictRecord(SQLModel, table=True):
    """
    Stores both versions when a sync conflict is detected.
    The user resolves via UI (side-by-side diff).
    """

    __tablename__ = "sync_conflicts"

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    tenant_id: UUID = Field(nullable=False, index=True)
    user_id: Optional[UUID] = Field(default=None)

    # Link to the sync operation that triggered the conflict
    sync_op_id: UUID = Field(nullable=False, index=True)

    # Divergent data
    resource_type: str = Field(max_length=100, nullable=False)
    resource_id: str = Field(max_length=200, nullable=False)
    client_data: Dict[str, Any] = Field(
        default_factory=dict, sa_column=Column(JSON)
    )
    server_data: Dict[str, Any] = Field(
        default_factory=dict, sa_column=Column(JSON)
    )
    client_ts: datetime = Field(nullable=False)
    server_ts: datetime = Field(nullable=False)

    # Resolution
    resolved: bool = Field(default=False, index=True)
    resolution_strategy: Optional[ConflictResolutionStrategy] = Field(default=None)
    resolved_data: Optional[Dict[str, Any]] = Field(
        default=None, sa_column=Column(JSON)
    )
    resolved_by: Optional[str] = Field(default=None, max_length=100)
    resolved_at: Optional[datetime] = Field(default=None)

    # Audit
    detected_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False)