aboutsummaryrefslogtreecommitdiff
path: root/processor.go
blob: 1079e3d75b90938522154e378d31aea5d6e7dc8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// PROCESSING PIPELINE
//
// Handles batch processing of URLs with rate limiting and fallback strategies.
// 
// DESIGN:
// - fixed chunk size (50) to balance API efficiency and error recovery
// - batching for arxiv/s2 APIs, individual fallback on batch failure
// - sep handlers for each route type (arxiv, s2, rawhtml)
// - JSONL logging of every attempt (success/failure) with timestamps
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"time"
)

type ProcessResult struct {
	ArticlesWritten int
	Errors          int
}

type URLLogEntry struct {
	Time    string `json:"time"`
	URL     string `json:"url"`
	Success int    `json:"success"`
	API     string `json:"api"`
	Error   string `json:"error,omitempty"`
}

func logArticleAttempt(logEncoder *json.Encoder, url, api string, err error) error {
	success := 0
	errMsg := ""
	if err == nil {
		success = 1
	} else {
		errMsg = err.Error()
	}
	return logEncoder.Encode(URLLogEntry{
		Time:    time.Now().Format(time.RFC3339),
		URL:     url,
		Success: success,
		API:     api,
		Error:   errMsg,
	})
}

func logEncodingFailure(logEncoder *json.Encoder, url string, err error) error {
	return logEncoder.Encode(URLLogEntry{
		Time:    time.Now().Format(time.RFC3339),
		URL:     url,
		Success: 0,
		API:     "",
		Error:   fmt.Sprintf("encoding error: %v", err),
	})
}

// ProcessURLsWithConfig orchestrates the entire processing pipeline
// chunks URLs to balance API efficiency with error recovery
func ProcessURLsWithConfig(urls []string, config *Config, encoder *json.Encoder, logFile io.Writer) ProcessResult {
	result := ProcessResult{}
	ctx := context.Background()
	logEncoder := json.NewEncoder(logFile)

	chunkSize := 50

	processedCount := 0

	// process URLs in chunks
	for i := 0; i < len(urls); i += chunkSize {
		end := i + chunkSize
		if end > len(urls) {
			end = len(urls)
		}

		chunk := urls[i:end]
		
		if config.Verbose && config.Logger != nil {
			config.Logger.Printf("Processing chunk %d-%d of %d URLs", i+1, end, len(urls))
		}

		// do the work
		chunkResult := processChunk(ctx, chunk, config, encoder, logEncoder)
		
		result.ArticlesWritten += chunkResult.ArticlesWritten
		result.Errors += chunkResult.Errors
		processedCount += len(chunk)

		if config.Verbose && config.Logger != nil {
			fmt.Fprintf(os.Stderr, "Processed %d articles...\n", processedCount)
		}
	}

	return result
}

// processChunk handles routing, batching, and fallback for a given chunk of URLs.
func processChunk(ctx context.Context, urls []string, config *Config, encoder *json.Encoder, logEncoder *json.Encoder) ProcessResult {
	result := ProcessResult{}

	// create temporary articles for routing and processing
	articles := make([]*Article, len(urls))
	for i, url := range urls {
		articles[i] = &Article{URL: url}
	}

	// 1. toute all articles in the chunk
	for _, article := range articles {
		routeArticle(article)
	}

	// 2. group by type for batching
	arxivURLs := []string{}
	s2URLs := []string{}
	htmlURLs := []string{}

	for _, article := range articles {
		switch article.Route {
		case "arxiv":
			arxivURLs = append(arxivURLs, article.URL)
		case "s2":
			s2URLs = append(s2URLs, article.URL)
		default:
			htmlURLs = append(htmlURLs, article.URL)
		}
	}

	// 3. process each type (lim to chunk size)
	if len(arxivURLs) > 0 {
		if config.Verbose && config.Logger != nil {
			config.Logger.Printf("Processing %d arXiv URLs in chunk", len(arxivURLs))
		}
		n, err := processArxiv(ctx, arxivURLs, encoder, config, logEncoder)
		result.ArticlesWritten += n
		if err != nil {
			result.Errors++
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error processing arXiv URLs: %v", err)
			}
		}
	}

	if len(s2URLs) > 0 {
		if config.Verbose && config.Logger != nil {
			config.Logger.Printf("Processing %d Semantic Scholar URLs in chunk", len(s2URLs))
		}
		n, err := processSemanticScholar(ctx, s2URLs, encoder, config, logEncoder)
		result.ArticlesWritten += n
		if err != nil {
			result.Errors++
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error processing S2 URLs: %v", err)
			}
		}
	}

	if len(htmlURLs) > 0 {
		if config.Verbose && config.Logger != nil {
			config.Logger.Printf("Processing %d raw HTML URLs in chunk", len(htmlURLs))
		}
		n, err := processHTML(ctx, htmlURLs, encoder, config, logEncoder)
		result.ArticlesWritten += n
		if err != nil {
			result.Errors++
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error processing HTML URLs: %v", err)
			}
		}
	}

	return result
}

func processArxiv(ctx context.Context, urls []string, encoder *json.Encoder, config *Config, logEncoder *json.Encoder) (int, error) {
	articles, err := fetchArxivBatch(ctx, config, urls)
	if err != nil {
		if config.Verbose && config.Logger != nil {
			config.Logger.Printf("arXiv batch failed: %v, falling back to individual processing", err)
		}
		return processIndividualArxiv(ctx, urls, encoder, config, logEncoder)
	}

	written := 0
	for _, article := range articles {
		if err := encoder.Encode(article); err != nil {
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error encoding article: %v", err)
			}
			_ = logEncodingFailure(logEncoder, article.URL, err)
		} else {
			written++
			_ = logArticleAttempt(logEncoder, article.URL, "arxiv", nil)
		}
	}
	return written, nil
}

func processSemanticScholar(ctx context.Context, urls []string, encoder *json.Encoder, config *Config, logEncoder *json.Encoder) (int, error) {
	articles, err := fetchSemanticScholarBatch(ctx, config, urls)
	if err != nil {
		if config.Verbose && config.Logger != nil {
			config.Logger.Printf("S2 batch failed: %v, falling back to individual processing", err)
		}
		return processIndividualS2(ctx, urls, encoder, config, logEncoder)
	}

	written := 0
	for _, article := range articles {
		if err := encoder.Encode(article); err != nil {
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error encoding article: %v", err)
			}
			_ = logEncodingFailure(logEncoder, article.URL, err)
		} else {
			written++
			_ = logArticleAttempt(logEncoder, article.URL, "s2", nil)
		}
	}
	return written, nil
}

func processHTML(ctx context.Context, urls []string, encoder *json.Encoder, config *Config, logEncoder *json.Encoder) (int, error) {
	written := 0
	for _, url := range urls {
		article, err := fetchRawHTML(ctx, config, url)
		if err != nil {
			_ = logArticleAttempt(logEncoder, url, "", err)
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error fetching HTML %s: %v", url, err)
			}
			continue
		}
		if err := encoder.Encode(article); err != nil {
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error encoding article: %v", err)
			}
			_ = logEncodingFailure(logEncoder, url, err)
		} else {
			written++
			_ = logArticleAttempt(logEncoder, url, "html", nil)
		}
	}
	return written, nil
}

func processIndividualArxiv(ctx context.Context, urls []string, encoder *json.Encoder, config *Config, logEncoder *json.Encoder) (int, error) {
	written := 0
	for _, url := range urls {
		article, err := fetchArxiv(ctx, config, url)
		if err != nil {
			_ = logArticleAttempt(logEncoder, url, "", err)
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error fetching arXiv %s: %v", url, err)
			}
			continue
		}
		if err := encoder.Encode(article); err != nil {
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error encoding article: %v", err)
			}
			_ = logEncodingFailure(logEncoder, url, err)
		} else {
			written++
			_ = logArticleAttempt(logEncoder, url, "arxiv", nil)
		}
	}
	return written, nil
}

func processIndividualS2(ctx context.Context, urls []string, encoder *json.Encoder, config *Config, logEncoder *json.Encoder) (int, error) {
	written := 0
	for _, url := range urls {
		article, err := fetchSemanticScholar(ctx, config, url)
		if err != nil {
			_ = logArticleAttempt(logEncoder, url, "", err)
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error fetching S2 %s: %v", url, err)
			}
			continue
		}
		if err := encoder.Encode(article); err != nil {
			if config.Verbose && config.Logger != nil {
				config.Logger.Printf("Error encoding article: %v", err)
			}
			_ = logEncodingFailure(logEncoder, url, err)
		} else {
			written++
			_ = logArticleAttempt(logEncoder, url, "s2", nil)
		}
	}
	return written, nil
}