Refaktor: riktig dataflyt — SpacetimeDB er master for body-endring
Før: worker skrev body til både PG og SpacetimeDB (dobbelt-skriving), og sync.rs skrev den samme endringen tilbake fra SpacetimeDB til PG. Nå: worker skriver body-endring KUN til SpacetimeDB, sync.rs synker til PG som vanlig. Worker skriver kun PG-only data direkte (metadata, revisjoner, tokenforbruk). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
b4e01feada
commit
3ac9691830
1 changed files with 26 additions and 28 deletions
|
|
@ -155,7 +155,32 @@ impl JobHandler for AiTextProcessHandler {
|
|||
.await
|
||||
.context("AI Gateway-kall feilet")?;
|
||||
|
||||
// 6. Logg tokenforbruk til ai_usage_log
|
||||
// 6. Oppdater SpacetimeDB — dette er primær-kanalen til frontend.
|
||||
// sync.rs synker body-endringen til PG automatisk.
|
||||
self.update_spacetimedb(&message_id, workspace_id, &ai_resp.content)
|
||||
.await
|
||||
.context("Kunne ikke oppdatere SpacetimeDB med AI-resultat")?;
|
||||
|
||||
// 7. Skriv PG-only data (metadata, revisjon er allerede lagret, tokenforbruk)
|
||||
let metadata = json!({
|
||||
"ai_processed": true,
|
||||
"ai_action": action
|
||||
});
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE messages
|
||||
SET metadata = (COALESCE(metadata, '{}'::jsonb) - 'ai_processing') || $1::jsonb
|
||||
WHERE id = $2
|
||||
"#,
|
||||
)
|
||||
.bind(metadata)
|
||||
.bind(message_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.context("Feil ved oppdatering av metadata")?;
|
||||
|
||||
// 8. Logg tokenforbruk til ai_usage_log
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO ai_usage_log (workspace_id, job_id, job_type, model_alias, model_actual, prompt_tokens, completion_tokens, total_tokens)
|
||||
|
|
@ -173,33 +198,6 @@ impl JobHandler for AiTextProcessHandler {
|
|||
.await
|
||||
.context("Feil ved logging av tokenforbruk")?;
|
||||
|
||||
// 7. Oppdater meldingens body med AI-resultat, fjern ai_processing
|
||||
let metadata = json!({
|
||||
"ai_processed": true,
|
||||
"ai_action": action
|
||||
});
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE messages
|
||||
SET body = $1,
|
||||
edited_at = now(),
|
||||
metadata = (COALESCE(metadata, '{}'::jsonb) - 'ai_processing') || $2::jsonb
|
||||
WHERE id = $3
|
||||
"#,
|
||||
)
|
||||
.bind(&ai_resp.content)
|
||||
.bind(metadata)
|
||||
.bind(message_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.context("Feil ved oppdatering av melding")?;
|
||||
|
||||
// 8. Oppdater SpacetimeDB slik at frontend ser endringen
|
||||
if let Err(e) = self.update_spacetimedb(&message_id, workspace_id, &ai_resp.content).await {
|
||||
warn!(error = %e, "Kunne ikke oppdatere SpacetimeDB — PG er oppdatert, frontend oppdateres ved neste reload");
|
||||
}
|
||||
|
||||
info!(
|
||||
message_id = %message_id,
|
||||
action = action,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue