Sobes.tech
Senior

Gli aggiornamenti dei documenti arrivano al servizio message Document { string Url = 1; // URL del documento, il suo identificatore univoco uint64 PubDate = 2; // ora di pubblicazione dichiarata del documento uint64 FetchTime = 3; // ora di ricezione di questo aggiornamento del documento, può essere considerato come identificatore di versione. La coppia (Url, FetchTime) è unica. string Text = 4; // testo del documento uint64 FirstFetchTime = 5; // inizialmente assente, deve essere compilato } I documenti possono arrivare in qualsiasi ordine (non nell'ordine in cui sono stati aggiornati), e possono esserci messaggi duplicati. È necessario, in uscita, formare messaggi uguali, ma con campi corretti secondo le seguenti regole (tutto quanto sotto vale per un gruppo di documenti con lo stesso campo Url): Il campo Text e FetchTime devono essere uguali a quelli del documento con il FetchTime più grande ricevuto finora. Il campo PubDate deve essere uguale a quello del messaggio con il FetchTime più piccolo. Il campo FirstFetchTime deve essere uguale al valore minimo di FetchTime. In altre parole, in ogni momento prendiamo PubDate e FirstFetchTime dalla prima versione ricevuta finora (se ordiniamo per FetchTime), e Text dall'ultima. L'interfaccia nel codice può essere implementata così: type Processor interface { Process(doc *Document) (*Document, error) } Questo codice funzionerà in un servizio che legge messaggi da una coda (Kafka o simile), e scrive anche il risultato nella coda. Se Process restituisce Null, nulla viene scritto nella coda.

sobes.tech AI

Risposta dell'AI

Для реализации интерфейса Processor в Go нужно хранить состояние по каждому Url, чтобы на каждый входящий документ обновлять агрегированное состояние и возвращать скорректированное сообщение.

Основная идея:

  • Для каждого Url хранить:
    • минимальный FetchTime (для PubDate и FirstFetchTime)
    • максимальный FetchTime (для Text и FetchTime)
    • PubDate, Text, FirstFetchTime, соответствующие этим минимальному и максимальному FetchTime

При получении нового документа:

  • Если для Url нет записи — создать с данными из документа
  • Иначе обновить минимальный и максимальный FetchTime и соответствующие поля при необходимости
  • Вернуть агрегированный документ с нужными полями

Пример реализации:

import (
    "errors"
    "sync"
)

type Document struct {
    Url            string
    PubDate        uint64
    FetchTime      uint64
    Text           string
    FirstFetchTime uint64
}

type Processor interface {
    Process(doc *Document) (*Document, error)
}

type docState struct {
    minFetchTime uint64
    maxFetchTime uint64
    pubDate      uint64
    text         string
    firstFetch   uint64
}

type processorImpl struct {
    mu    sync.Mutex
    state map[string]*docState
}

func NewProcessor() Processor {
    return &processorImpl{
        state: make(map[string]*docState),
    }
}

func (p *processorImpl) Process(doc *Document) (*Document, error) {
    if doc == nil {
        return nil, errors.New("input document is nil")
    }

    p.mu.Lock()
    defer p.mu.Unlock()

    st, ok := p.state[doc.Url]
    if !ok {
        // первый документ для данного Url
        p.state[doc.Url] = &docState{
            minFetchTime: doc.FetchTime,
            maxFetchTime: doc.FetchTime,
            pubDate:      doc.PubDate,
            text:         doc.Text,
            firstFetch:   doc.FetchTime,
        }
        return &Document{
            Url:            doc.Url,
            PubDate:        doc.PubDate,
            FetchTime:      doc.FetchTime,
            Text:           doc.Text,
            FirstFetchTime: doc.FetchTime,
        }, nil
    }

    updated := false

    // Обновляем минимальный FetchTime и PubDate, FirstFetchTime
    if doc.FetchTime < st.minFetchTime {
        st.minFetchTime = doc.FetchTime
        st.pubDate = doc.PubDate
        st.firstFetch = doc.FetchTime
        updated = true
    }

    // Обновляем максимальный FetchTime и Text
    if doc.FetchTime > st.maxFetchTime {
        st.maxFetchTime = doc.FetchTime
        st.text = doc.Text
        updated = true
    }

    // Если пришло сообщение с FetchTime, который уже есть, но текст или PubDate отличаются,
    // можно игнорировать, так как пара (Url, FetchTime) уникальна, либо обновлять по логике.

    if !updated {
        // Данные не изменились, можно вернуть nil, чтобы не писать в очередь
        return nil, nil
    }

    return &Document{
        Url:            doc.Url,
        PubDate:        st.pubDate,
        FetchTime:      st.maxFetchTime,
        Text:           st.text,
        FirstFetchTime: st.firstFetch,
    }, nil
}

Таким образом, сервис будет поддерживать актуальное агрегированное состояние для каждого Url и возвращать скорректированные документы согласно правилам.