Jacksuyu commited on
Commit
cfa8023
·
1 Parent(s): 851ed7a

fix: use Reddit OAuth in workflow collector and improve fetch resilience

Browse files
.env.example CHANGED
@@ -1,6 +1,9 @@
1
  DATABASE_URL="postgresql://postgres:[PASSWORD]@[HOST]:5432/postgres?sslmode=require"
2
  OPENAI_API_KEY=""
3
  OPENAI_MODEL="gpt-4.1-mini"
 
 
 
4
 
5
  AUTH_SECRET="replace-with-long-random-secret"
6
  AUTH_URL="http://localhost:3000"
 
1
  DATABASE_URL="postgresql://postgres:[PASSWORD]@[HOST]:5432/postgres?sslmode=require"
2
  OPENAI_API_KEY=""
3
  OPENAI_MODEL="gpt-4.1-mini"
4
+ REDDIT_CLIENT_ID=""
5
+ REDDIT_CLIENT_SECRET=""
6
+ REDDIT_USER_AGENT="demand-sync-local/1.0 by u/your_reddit_username"
7
 
8
  AUTH_SECRET="replace-with-long-random-secret"
9
  AUTH_URL="http://localhost:3000"
.github/workflows/daily-social-requirements.yml CHANGED
@@ -13,6 +13,9 @@ jobs:
13
  runs-on: ubuntu-latest
14
  env:
15
  OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
 
 
 
16
  OPENAI_MODEL: gpt-4o-mini
17
  SITE_URL: ${{ vars.DEMANDSOLUTION_SITE_URL }}
18
  steps:
@@ -37,6 +40,18 @@ jobs:
37
  echo "Missing required repository variable: DEMANDSOLUTION_SITE_URL"
38
  exit 1
39
  fi
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  - name: Collect Reddit demand signals
42
  run: |
@@ -45,7 +60,8 @@ jobs:
45
  --sort new \
46
  --per-subreddit 50 \
47
  --search-per-query 15 \
48
- --hours 48
 
49
 
50
  - name: Resolve latest run directory
51
  id: run_dir
 
13
  runs-on: ubuntu-latest
14
  env:
15
  OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
16
+ REDDIT_CLIENT_ID: ${{ secrets.REDDIT_CLIENT_ID }}
17
+ REDDIT_CLIENT_SECRET: ${{ secrets.REDDIT_CLIENT_SECRET }}
18
+ REDDIT_USER_AGENT: ${{ vars.REDDIT_USER_AGENT }}
19
  OPENAI_MODEL: gpt-4o-mini
20
  SITE_URL: ${{ vars.DEMANDSOLUTION_SITE_URL }}
21
  steps:
 
40
  echo "Missing required repository variable: DEMANDSOLUTION_SITE_URL"
41
  exit 1
42
  fi
43
+ if [ -z "${REDDIT_CLIENT_ID}" ]; then
44
+ echo "Missing required secret: REDDIT_CLIENT_ID"
45
+ exit 1
46
+ fi
47
+ if [ -z "${REDDIT_CLIENT_SECRET}" ]; then
48
+ echo "Missing required secret: REDDIT_CLIENT_SECRET"
49
+ exit 1
50
+ fi
51
+ if [ -z "${REDDIT_USER_AGENT}" ]; then
52
+ echo "Missing required repository variable: REDDIT_USER_AGENT"
53
+ exit 1
54
+ fi
55
 
56
  - name: Collect Reddit demand signals
57
  run: |
 
60
  --sort new \
61
  --per-subreddit 50 \
62
  --search-per-query 15 \
63
+ --hours 48 \
64
+ --user-agent "${REDDIT_USER_AGENT}"
65
 
66
  - name: Resolve latest run directory
67
  id: run_dir
README.md CHANGED
@@ -93,3 +93,6 @@ Required GitHub repository settings:
93
 
94
  - Secret: `OPENAI_API_KEY`
95
  - Variable: `DEMANDSOLUTION_SITE_URL` (example: `https://jacksuyu-demandsolution-codex.hf.space/`)
 
 
 
 
93
 
94
  - Secret: `OPENAI_API_KEY`
95
  - Variable: `DEMANDSOLUTION_SITE_URL` (example: `https://jacksuyu-demandsolution-codex.hf.space/`)
96
+ - Secret: `REDDIT_CLIENT_ID`
97
+ - Secret: `REDDIT_CLIENT_SECRET`
98
+ - Variable: `REDDIT_USER_AGENT` (example: `demand-sync-bot/1.0 by u/<your_reddit_username>`)
src/web_user_summary/cli.py CHANGED
@@ -60,16 +60,35 @@ def main() -> None:
60
  client = RedditClient(user_agent=args.user_agent)
61
  search_queries = parse_csv_terms(args.search_queries)
62
  all_posts = []
 
63
  for subreddit in subreddits:
64
- posts = client.fetch_subreddit_posts(subreddit=subreddit, sort=args.sort, limit=args.per_subreddit)
 
 
 
 
 
 
 
65
  all_posts.extend(posts)
66
  print(f"Fetched {len(posts):>3} posts from r/{subreddit}")
67
  for query in search_queries:
68
- q_posts = client.fetch_subreddit_search(
69
- subreddit=subreddit, query=query, sort=args.sort, limit=args.search_per_query
70
- )
71
- all_posts.extend(q_posts)
72
- print(f" + search '{query}': {len(q_posts):>3} posts")
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  # Deduplicate by post ID
75
  dedup = {}
@@ -104,6 +123,8 @@ def main() -> None:
104
  print(f"Total posts: {meta['total_posts']}")
105
  print(f"Demand candidates: {meta['total_candidates']}")
106
  print(f"Demand clusters: {meta['total_clusters']}")
 
 
107
 
108
 
109
  if __name__ == "__main__":
 
60
  client = RedditClient(user_agent=args.user_agent)
61
  search_queries = parse_csv_terms(args.search_queries)
62
  all_posts = []
63
+ fetch_failures = []
64
  for subreddit in subreddits:
65
+ try:
66
+ posts = client.fetch_subreddit_posts(subreddit=subreddit, sort=args.sort, limit=args.per_subreddit)
67
+ except Exception as exc:
68
+ message = f"Failed listing r/{subreddit}: {exc}"
69
+ fetch_failures.append(message)
70
+ print(f"[WARN] {message}")
71
+ continue
72
+
73
  all_posts.extend(posts)
74
  print(f"Fetched {len(posts):>3} posts from r/{subreddit}")
75
  for query in search_queries:
76
+ try:
77
+ q_posts = client.fetch_subreddit_search(
78
+ subreddit=subreddit, query=query, sort=args.sort, limit=args.search_per_query
79
+ )
80
+ all_posts.extend(q_posts)
81
+ print(f" + search '{query}': {len(q_posts):>3} posts")
82
+ except Exception as exc:
83
+ message = f"Failed search r/{subreddit} query='{query}': {exc}"
84
+ fetch_failures.append(message)
85
+ print(f"[WARN] {message}")
86
+
87
+ if not all_posts:
88
+ raise RuntimeError(
89
+ "No Reddit posts were fetched. In GitHub Actions, set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET "
90
+ "repository secrets, and set REDDIT_USER_AGENT as a repository variable."
91
+ )
92
 
93
  # Deduplicate by post ID
94
  dedup = {}
 
123
  print(f"Total posts: {meta['total_posts']}")
124
  print(f"Demand candidates: {meta['total_candidates']}")
125
  print(f"Demand clusters: {meta['total_clusters']}")
126
+ if fetch_failures:
127
+ print(f"Warnings: {len(fetch_failures)} fetch calls failed but pipeline continued.")
128
 
129
 
130
  if __name__ == "__main__":
src/web_user_summary/reddit_client.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  import time
4
  from typing import Dict, List, Optional
5
 
@@ -9,9 +10,17 @@ from .models import RedditPost
9
 
10
 
11
  class RedditClient:
12
- def __init__(self, user_agent: str, timeout_s: int = 20, max_retries: int = 4) -> None:
 
 
 
 
 
 
 
13
  self.timeout_s = timeout_s
14
  self.max_retries = max_retries
 
15
  self.session = requests.Session()
16
  self.session.headers.update(
17
  {
@@ -19,16 +28,75 @@ class RedditClient:
19
  "Accept": "application/json",
20
  }
21
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def _request_json(self, url: str, params: Dict) -> Dict:
24
  last_error: Optional[Exception] = None
 
 
 
25
  for attempt in range(1, self.max_retries + 1):
26
  try:
27
- response = self.session.get(url, params=params, timeout=self.timeout_s)
28
- if response.status_code == 429:
 
 
 
 
 
 
 
 
29
  sleep_s = min(12, 2 * attempt)
30
  time.sleep(sleep_s)
31
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  response.raise_for_status()
33
  return response.json()
34
  except Exception as exc:
@@ -36,7 +104,10 @@ class RedditClient:
36
  if attempt < self.max_retries:
37
  time.sleep(1.3 * attempt)
38
  else:
39
- raise RuntimeError(f"Reddit request failed after retries: {url}") from last_error
 
 
 
40
  raise RuntimeError(f"Unexpected request failure: {url}")
41
 
42
  def fetch_subreddit_posts(self, subreddit: str, sort: str = "new", limit: int = 100) -> List[RedditPost]:
 
1
  from __future__ import annotations
2
 
3
+ import os
4
  import time
5
  from typing import Dict, List, Optional
6
 
 
10
 
11
 
12
  class RedditClient:
13
+ def __init__(
14
+ self,
15
+ user_agent: str,
16
+ timeout_s: int = 20,
17
+ max_retries: int = 4,
18
+ client_id: Optional[str] = None,
19
+ client_secret: Optional[str] = None,
20
+ ) -> None:
21
  self.timeout_s = timeout_s
22
  self.max_retries = max_retries
23
+ self.user_agent = user_agent
24
  self.session = requests.Session()
25
  self.session.headers.update(
26
  {
 
28
  "Accept": "application/json",
29
  }
30
  )
31
+ self.client_id = (client_id or os.getenv("REDDIT_CLIENT_ID", "")).strip()
32
+ self.client_secret = (client_secret or os.getenv("REDDIT_CLIENT_SECRET", "")).strip()
33
+ self.use_oauth = bool(self.client_id and self.client_secret)
34
+ self.oauth_access_token: Optional[str] = None
35
+ self.oauth_expires_at = 0.0
36
+
37
+ def _fetch_oauth_token(self) -> None:
38
+ if not self.use_oauth:
39
+ return
40
+
41
+ response = self.session.post(
42
+ "https://www.reddit.com/api/v1/access_token",
43
+ auth=(self.client_id, self.client_secret),
44
+ data={"grant_type": "client_credentials"},
45
+ headers={"User-Agent": self.user_agent},
46
+ timeout=self.timeout_s,
47
+ )
48
+ response.raise_for_status()
49
+ payload = response.json()
50
+ token = payload.get("access_token")
51
+ expires_in = int(payload.get("expires_in", 3600))
52
+ if not token:
53
+ raise RuntimeError("Reddit OAuth token response did not include access_token")
54
+
55
+ self.oauth_access_token = str(token)
56
+ self.oauth_expires_at = time.time() + max(60, expires_in - 60)
57
+
58
+ def _ensure_oauth_token(self) -> None:
59
+ if not self.use_oauth:
60
+ return
61
+ if self.oauth_access_token and time.time() < self.oauth_expires_at:
62
+ return
63
+ self._fetch_oauth_token()
64
 
65
  def _request_json(self, url: str, params: Dict) -> Dict:
66
  last_error: Optional[Exception] = None
67
+ using_oauth = self.use_oauth
68
+ oauth_url = url.replace("https://www.reddit.com", "https://oauth.reddit.com", 1) if using_oauth else url
69
+
70
  for attempt in range(1, self.max_retries + 1):
71
  try:
72
+ headers: Dict[str, str] = {}
73
+ request_url = url
74
+ if using_oauth:
75
+ self._ensure_oauth_token()
76
+ request_url = oauth_url
77
+ headers["Authorization"] = f"bearer {self.oauth_access_token}"
78
+
79
+ response = self.session.get(request_url, params=params, headers=headers or None, timeout=self.timeout_s)
80
+
81
+ if response.status_code in {429, 500, 502, 503, 504}:
82
  sleep_s = min(12, 2 * attempt)
83
  time.sleep(sleep_s)
84
  continue
85
+
86
+ if response.status_code in {401, 403} and using_oauth:
87
+ # Token might be expired or revoked mid-run; refresh and retry.
88
+ self.oauth_access_token = None
89
+ self.oauth_expires_at = 0.0
90
+ if attempt < self.max_retries:
91
+ time.sleep(1.2 * attempt)
92
+ continue
93
+
94
+ if response.status_code == 403 and not using_oauth:
95
+ raise RuntimeError(
96
+ "Reddit returned 403 (blocked). Configure REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET "
97
+ "for OAuth-based access from GitHub Actions."
98
+ )
99
+
100
  response.raise_for_status()
101
  return response.json()
102
  except Exception as exc:
 
104
  if attempt < self.max_retries:
105
  time.sleep(1.3 * attempt)
106
  else:
107
+ auth_hint = (
108
+ " OAuth mode was enabled." if using_oauth else " OAuth mode was not enabled."
109
+ )
110
+ raise RuntimeError(f"Reddit request failed after retries: {url}.{auth_hint}") from last_error
111
  raise RuntimeError(f"Unexpected request failure: {url}")
112
 
113
  def fetch_subreddit_posts(self, subreddit: str, sort: str = "new", limit: int = 100) -> List[RedditPost]: