Sobes.tech
Senior

Las actualizaciones de documentos llegan al servicio mensaje Documento { string Url = 1; // URL del documento, su identificador único uint64 PubDate = 2; // tiempo de publicación declarado del documento uint64 FetchTime = 3; // tiempo de recepción de esta actualización del documento, puede considerarse como identificador de versión. El par (Url, FetchTime) es único. string Text = 4; // texto del documento uint64 FirstFetchTime = 5; // inicialmente ausente, debe completarse } Los documentos pueden llegar en cualquier orden (no en el orden en que fueron actualizados), y también puede haber mensajes duplicados. Es necesario en la salida formar mensajes iguales, pero con campos corregidos según las siguientes reglas (todo lo mencionado a continuación es para un grupo de documentos con el mismo campo Url): El campo Text y FetchTime deben ser iguales a los del documento con el mayor FetchTime recibido hasta ahora. El campo PubDate debe ser igual al del mensaje con el menor FetchTime. El campo FirstFetchTime debe ser igual al valor mínimo de FetchTime. Es decir, en cada momento tomamos PubDate y FirstFetchTime del primer versión recibida hasta ahora (si las ordenamos por FetchTime), y Text de la última. La interfaz en el código puede implementarse así: type Processor interface { Process(doc *Document) (*Document, error) } Este código funcionará en un servicio que lee mensajes de una cola (Kafka o similar), y también escribe el resultado en la cola. Si Process devuelve Null, no se escribe nada en la cola.

sobes.tech AI

Respuesta de la IA

Для реализации интерфейса 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 и возвращать скорректированные документы согласно правилам.