feat(market): analytics of downloads

This commit is contained in:
Nicholas Tindle
2024-07-31 16:44:44 -05:00
parent 2ac5868b24
commit 217b691a48
5 changed files with 46 additions and 5 deletions

View File

@@ -2,12 +2,13 @@ import json
from tempfile import NamedTemporaryFile
from typing import Literal, Optional
from fastapi import APIRouter, HTTPException, Path, Query
from fastapi import APIRouter, BackgroundTasks, HTTPException, Path, Query
from fastapi.responses import FileResponse
from prisma import Json
import market.model
from market.db import AgentQueryError, get_agent_details, get_agents
from market.utils.analytics import track_download
router = APIRouter()
@@ -114,6 +115,7 @@ async def get_agent_details_endpoint(
@router.get("/agents/{agent_id}/download")
async def download_agent(
background_tasks: BackgroundTasks,
agent_id: str = Path(..., description="The ID of the agent to download"),
version: Optional[int] = Query(None, description="Specific version of the agent"),
) -> FileResponse:
@@ -130,12 +132,13 @@ async def download_agent(
Raises:
HTTPException: If the agent is not found or an unexpected error occurs.
"""
# try:
agent = await get_agent_details(agent_id, version)
# The agent.graph is already a JSON string, no need to parse and re-stringify
graph_data: Json = agent.graph
background_tasks.add_task(track_download, agent_id)
# Prepare the file name for download
file_name = f"agent_{agent_id}_v{version or 'latest'}.json"

View File

@@ -0,0 +1,24 @@
from prisma.models import AnalyticsTracker
async def track_download(agent_id: str):
"""
Track the download event in the database.
Args:
agent_id (str): The ID of the agent.
version (int | None, optional): The version of the agent. Defaults to None.
Raises:
Exception: If there is an error tracking the download event.
"""
try:
await AnalyticsTracker.prisma().upsert(
where={"agentId": agent_id},
data={
"update": {"downloads": {"increment": 1}},
"create": {"agentId": agent_id, "downloads": 1, "views": 0},
},
)
except Exception as e:
raise Exception(f"Error tracking download event: {str(e)}")

View File

@@ -0,0 +1,11 @@
/*
Warnings:
- A unique constraint covering the columns `[agentId]` on the table `AnalyticsTracker` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE "AnalyticsTracker" ADD CONSTRAINT "AnalyticsTracker_pkey" PRIMARY KEY ("id");
-- CreateIndex
CREATE UNIQUE INDEX "AnalyticsTracker_agentId_key" ON "AnalyticsTracker"("agentId");

View File

@@ -2,7 +2,10 @@
name = "market"
version = "0.1.0"
description = ""
authors = ["SwiftyOS <craigswift13@gmail.com>"]
authors = [
"SwiftyOS <craigswift13@gmail.com>",
"Nicholas Tindle <spam@ntindle.com>",
]
readme = "README.md"
[tool.poetry.dependencies]

View File

@@ -33,8 +33,8 @@ model Agents {
}
model AnalyticsTracker {
id String @unique @default(dbgenerated("gen_random_uuid()")) @db.Uuid
agentId String @db.Uuid
id String @id @unique @default(dbgenerated("gen_random_uuid()")) @db.Uuid
agentId String @unique @db.Uuid
agent Agents @relation(fields: [agentId], references: [id])
views Int
downloads Int