|
| 1 | +from collections.abc import Iterable |
| 2 | + |
| 3 | +import msgspec |
| 4 | +import pymemcache |
| 5 | +from kafka import KafkaConsumer |
| 6 | +from kafka.consumer.fetcher import ConsumerRecord |
| 7 | + |
| 8 | +from app.config import config |
| 9 | + |
| 10 | + |
| 11 | +class ChiiInterest(msgspec.Struct): |
| 12 | + interest_id: int |
| 13 | + interest_uid: int |
| 14 | + interest_subject_id: int |
| 15 | + interest_subject_type: int |
| 16 | + interest_rate: int |
| 17 | + interest_type: int |
| 18 | + interest_has_comment: int |
| 19 | + interest_comment: str |
| 20 | + interest_tag: str |
| 21 | + interest_ep_status: int |
| 22 | + interest_vol_status: int |
| 23 | + interest_wish_dateline: int |
| 24 | + interest_doing_dateline: int |
| 25 | + interest_collect_dateline: int |
| 26 | + interest_on_hold_dateline: int |
| 27 | + interest_dropped_dateline: int |
| 28 | + interest_create_ip: str |
| 29 | + interest_lasttouch_ip: str |
| 30 | + interest_lasttouch: int |
| 31 | + interest_private: int |
| 32 | + |
| 33 | + |
| 34 | +class ValuePayload(msgspec.Struct): |
| 35 | + before: ChiiInterest | None |
| 36 | + after: ChiiInterest | None |
| 37 | + op: str |
| 38 | + |
| 39 | + |
| 40 | +class Value(msgspec.Struct): |
| 41 | + payload: ValuePayload |
| 42 | + |
| 43 | + |
| 44 | +def kafka_events() -> Iterable[tuple[int, int]]: |
| 45 | + consumer = KafkaConsumer( |
| 46 | + "debezium.chii.bangumi.chii_subject_interests", |
| 47 | + group_id="py-cache-clean", |
| 48 | + bootstrap_servers=f"{config.broker.host}:{config.broker.port}", |
| 49 | + auto_offset_reset="earliest", |
| 50 | + ) |
| 51 | + |
| 52 | + msg: ConsumerRecord |
| 53 | + for msg in consumer: |
| 54 | + value = msgspec.json.decode(msg.value, type=Value) |
| 55 | + before = value.payload.before |
| 56 | + after = value.payload.after |
| 57 | + if after is not None: |
| 58 | + yield after.interest_uid, after.interest_subject_id |
| 59 | + elif before is not None: |
| 60 | + yield before.interest_uid, before.interest_subject_id |
| 61 | + |
| 62 | + |
| 63 | +def user_collection_change(): |
| 64 | + if config.broker.scheme == "kafka": |
| 65 | + yield from kafka_events() |
| 66 | + else: |
| 67 | + raise ValueError(f"event broker not support {config.broker.scheme!r}") |
| 68 | + |
| 69 | + |
| 70 | +def main(): |
| 71 | + client = pymemcache.Client(config.memcached) |
| 72 | + while True: |
| 73 | + for user_id, subject_id in kafka_events(): |
| 74 | + print(user_id, subject_id) |
| 75 | + client.delete(f"{user_id}:{subject_id}", True) |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments