|
| 1 | +import datetime |
| 2 | +import hashlib |
| 3 | + |
| 4 | +import redis |
| 5 | +from django.conf import settings |
| 6 | + |
| 7 | + |
| 8 | +class RTrendingWebFeed: |
| 9 | + """ |
| 10 | + Tracks web feed usage events: analyses, subscriptions, hint refinements, |
| 11 | + variant selections, and re-analyses. |
| 12 | +
|
| 13 | + Redis Key Structure: |
| 14 | + - wfAna:{date} -> sorted set {url_hash: count} for analyses |
| 15 | + - wfSub:{date} -> sorted set {url_hash: count} for subscriptions |
| 16 | + - wfAnaUsers:{date} -> set of user IDs who analyzed |
| 17 | + - wfSubUsers:{date} -> set of user IDs who subscribed |
| 18 | + - wfHints:{date} -> integer counter for hint/refine analyses |
| 19 | + - wfReanalyze:{date} -> integer counter for re-analyses |
| 20 | + - wfVariant:{date} -> sorted set {variant_index: count} |
| 21 | + - wfAnaSuccess:{date} -> integer counter for successful analyses |
| 22 | + - wfAnaFail:{date} -> integer counter for failed analyses |
| 23 | +
|
| 24 | + All keys expire after 35 days. |
| 25 | + """ |
| 26 | + |
| 27 | + TTL_DAYS = 35 |
| 28 | + |
| 29 | + @classmethod |
| 30 | + def _redis(cls): |
| 31 | + return redis.Redis(connection_pool=settings.REDIS_STATISTICS_POOL) |
| 32 | + |
| 33 | + @classmethod |
| 34 | + def _today(cls): |
| 35 | + return datetime.date.today().strftime("%Y-%m-%d") |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def _ttl(cls): |
| 39 | + return cls.TTL_DAYS * 24 * 60 * 60 |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def _url_hash(cls, url): |
| 43 | + return hashlib.sha256(url.encode("utf-8")).hexdigest()[:16] |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def record_analysis(cls, user_id, url, has_hint=False): |
| 47 | + r = cls._redis() |
| 48 | + today = cls._today() |
| 49 | + ttl = cls._ttl() |
| 50 | + url_hash = cls._url_hash(url) |
| 51 | + |
| 52 | + pipe = r.pipeline() |
| 53 | + pipe.zincrby(f"wfAna:{today}", 1, url_hash) |
| 54 | + pipe.expire(f"wfAna:{today}", ttl) |
| 55 | + pipe.sadd(f"wfAnaUsers:{today}", str(user_id)) |
| 56 | + pipe.expire(f"wfAnaUsers:{today}", ttl) |
| 57 | + if has_hint: |
| 58 | + pipe.incr(f"wfHints:{today}") |
| 59 | + pipe.expire(f"wfHints:{today}", ttl) |
| 60 | + pipe.execute() |
| 61 | + |
| 62 | + @classmethod |
| 63 | + def record_reanalysis(cls, user_id): |
| 64 | + r = cls._redis() |
| 65 | + today = cls._today() |
| 66 | + ttl = cls._ttl() |
| 67 | + |
| 68 | + pipe = r.pipeline() |
| 69 | + pipe.incr(f"wfReanalyze:{today}") |
| 70 | + pipe.expire(f"wfReanalyze:{today}", ttl) |
| 71 | + pipe.sadd(f"wfAnaUsers:{today}", str(user_id)) |
| 72 | + pipe.expire(f"wfAnaUsers:{today}", ttl) |
| 73 | + pipe.execute() |
| 74 | + |
| 75 | + @classmethod |
| 76 | + def record_analysis_result(cls, success=True): |
| 77 | + r = cls._redis() |
| 78 | + today = cls._today() |
| 79 | + ttl = cls._ttl() |
| 80 | + |
| 81 | + key = f"wfAnaSuccess:{today}" if success else f"wfAnaFail:{today}" |
| 82 | + pipe = r.pipeline() |
| 83 | + pipe.incr(key) |
| 84 | + pipe.expire(key, ttl) |
| 85 | + pipe.execute() |
| 86 | + |
| 87 | + @classmethod |
| 88 | + def record_subscription(cls, user_id, url, variant_index): |
| 89 | + r = cls._redis() |
| 90 | + today = cls._today() |
| 91 | + ttl = cls._ttl() |
| 92 | + url_hash = cls._url_hash(url) |
| 93 | + |
| 94 | + pipe = r.pipeline() |
| 95 | + pipe.zincrby(f"wfSub:{today}", 1, url_hash) |
| 96 | + pipe.expire(f"wfSub:{today}", ttl) |
| 97 | + pipe.sadd(f"wfSubUsers:{today}", str(user_id)) |
| 98 | + pipe.expire(f"wfSubUsers:{today}", ttl) |
| 99 | + pipe.zincrby(f"wfVariant:{today}", 1, str(variant_index)) |
| 100 | + pipe.expire(f"wfVariant:{today}", ttl) |
| 101 | + pipe.execute() |
| 102 | + |
| 103 | + @classmethod |
| 104 | + def get_daily_totals(cls, days=7): |
| 105 | + """Get daily totals for analyses, subscriptions, and unique users.""" |
| 106 | + r = cls._redis() |
| 107 | + results = [] |
| 108 | + |
| 109 | + for i in range(days): |
| 110 | + day = (datetime.date.today() - datetime.timedelta(days=i)).strftime("%Y-%m-%d") |
| 111 | + |
| 112 | + pipe = r.pipeline() |
| 113 | + pipe.zrange(f"wfAna:{day}", 0, -1, withscores=True) |
| 114 | + pipe.zrange(f"wfSub:{day}", 0, -1, withscores=True) |
| 115 | + pipe.scard(f"wfAnaUsers:{day}") |
| 116 | + vals = pipe.execute() |
| 117 | + |
| 118 | + analyses = sum(int(s) for _, s in vals[0]) |
| 119 | + subscriptions = sum(int(s) for _, s in vals[1]) |
| 120 | + unique_users = vals[2] |
| 121 | + |
| 122 | + results.append((day, analyses, subscriptions, unique_users)) |
| 123 | + |
| 124 | + return results |
| 125 | + |
| 126 | + @classmethod |
| 127 | + def get_stats_for_prometheus(cls): |
| 128 | + r = cls._redis() |
| 129 | + today = cls._today() |
| 130 | + |
| 131 | + pipe = r.pipeline() |
| 132 | + pipe.zrange(f"wfAna:{today}", 0, -1, withscores=True) # 0: analyses |
| 133 | + pipe.zrange(f"wfSub:{today}", 0, -1, withscores=True) # 1: subscriptions |
| 134 | + pipe.scard(f"wfAnaUsers:{today}") # 2: unique analyzing users |
| 135 | + pipe.scard(f"wfSubUsers:{today}") # 3: unique subscribing users |
| 136 | + pipe.get(f"wfHints:{today}") # 4: hints |
| 137 | + pipe.get(f"wfReanalyze:{today}") # 5: re-analyses |
| 138 | + pipe.zrange(f"wfVariant:{today}", 0, -1, withscores=True) # 6: variant choices |
| 139 | + pipe.get(f"wfAnaSuccess:{today}") # 7: successes |
| 140 | + pipe.get(f"wfAnaFail:{today}") # 8: failures |
| 141 | + vals = pipe.execute() |
| 142 | + |
| 143 | + analyses_total = sum(int(s) for _, s in vals[0]) |
| 144 | + unique_urls_analyzed = len(vals[0]) |
| 145 | + subscriptions_total = sum(int(s) for _, s in vals[1]) |
| 146 | + unique_urls_subscribed = len(vals[1]) |
| 147 | + unique_users_analyzing = vals[2] |
| 148 | + unique_users_subscribing = vals[3] |
| 149 | + hints = int(vals[4] or 0) |
| 150 | + reanalyses = int(vals[5] or 0) |
| 151 | + variant_choices = { |
| 152 | + (v.decode() if isinstance(v, bytes) else v): int(s) for v, s in vals[6] |
| 153 | + } |
| 154 | + successes = int(vals[7] or 0) |
| 155 | + failures = int(vals[8] or 0) |
| 156 | + |
| 157 | + conversion_pct = 0 |
| 158 | + if analyses_total > 0: |
| 159 | + conversion_pct = round(subscriptions_total / analyses_total * 100, 1) |
| 160 | + |
| 161 | + return { |
| 162 | + "analyses_today": analyses_total, |
| 163 | + "analyses_with_hint_today": hints, |
| 164 | + "reanalyses_today": reanalyses, |
| 165 | + "subscriptions_today": subscriptions_total, |
| 166 | + "unique_urls_analyzed_today": unique_urls_analyzed, |
| 167 | + "unique_urls_subscribed_today": unique_urls_subscribed, |
| 168 | + "unique_users_analyzing_today": unique_users_analyzing, |
| 169 | + "unique_users_subscribing_today": unique_users_subscribing, |
| 170 | + "analysis_success_today": successes, |
| 171 | + "analysis_fail_today": failures, |
| 172 | + "variant_choices": variant_choices, |
| 173 | + "conversion_rate_pct": conversion_pct, |
| 174 | + } |
0 commit comments