aboutsummaryrefslogtreecommitdiffstats
path: root/source/net/net_store.cpp
blob: 27f971af5a1bad4ff1f51feb7d80112569268058 (plain) (blame)
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//- paths

internal b32 make_directories(char *path)
{
	// NOTE: mkdir -p, modifies the buffer in place and restores it
	for(char *at = path + 1; *at; ++at) {
		if(*at == '/') {
			*at = 0;
			int result = mkdir(path, 0755);
			*at        = '/';
			if(result != 0 && errno != EEXIST) {
				return false;
			}
		}
	}
	return mkdir(path, 0755) == 0 || errno == EEXIST;
}

internal u32 store_track_path(TrackStore *store, u32 key, b32 partial, char *out, u32 out_size)
{
	Qari *qari  = &store->catalog->qaris[TrackQari(key)];
	int   count = snprintf(out, out_size, Str8Fmt "/" Str8Fmt "%03u.mp3%s",
	                       Str8Arg(store->audio_dir), Str8Arg(qari->relative_path),
	                       TrackSurah(key) + 1, partial ? ".part" : "");
	return (u32)count;
}

// NOTE: every write that can enter or leave DONE goes through here, so the per qari summary is
// exact. exchange, then adjust by what the state actually was.
internal void store_set_state(TrackStore *store, u32 key, TrackState state)
{
	if(key >= store->entry_count) return;
	u8  old  = AtomicExchange(&store->states[key], (u8)state);
	u32 qari = TrackQari(key);
	if(old != TRACK_DONE && state == TRACK_DONE) {
		AtomicAdd(&store->qari_done[qari], 1u);
		AtomicAdd(&store->qari_done_bytes[qari], AtomicLoad(&store->entries[key].bytes_total));
	} else if(old == TRACK_DONE && state != TRACK_DONE) {
		AtomicAdd(&store->qari_done[qari], (u32)-1);
		AtomicAdd(&store->qari_done_bytes[qari], (u64)0 - AtomicLoad(&store->entries[key].bytes_total));
	}
}

internal TrackEntry *store_entry(TrackStore *store, u32 key)
{
	return (key < store->entry_count) ? &store->entries[key] : NULL;
}

//- init and scan

internal void store_init(Arena *arena, TrackStore *store, Catalog *catalog, String8 data_dir)
{
	store->catalog     = catalog;
	store->entry_count = catalog->qari_count * SURAH_COUNT;
	store->entries     = PushArrayAligned(arena, TrackEntry, store->entry_count);
	store->states      = PushArrayAligned(arena, u8, store->entry_count);
	store->qari_done       = PushArrayAligned(arena, u32, catalog->qari_count);
	store->qari_done_bytes = PushArrayAligned(arena, u64, catalog->qari_count);
	store->qari_scanned = PushArrayZero(arena, u8, catalog->qari_count);

	u64 size         = data_dir.size + sizeof("/audio");
	u8 *buffer       = PushArray(arena, u8, size);
	int length       = snprintf((char *)buffer, size, Str8Fmt "/audio", Str8Arg(data_dir));
	store->audio_dir = ToString8Size(buffer, (u64)length);
	make_directories((char *)buffer);

	// NOTE: 2^15 = 32768 > 177 * 114, every track fits in the queue at once
	job_queue_init(arena, &store->queue, 1u << 15);
}

// NOTE: 114 stat()s, called lazily the first time a qari is looked at
internal void store_scan_qari(TrackStore *store, u32 qari_index)
{
	if(qari_index >= store->catalog->qari_count || store->qari_scanned[qari_index]) {
		return;
	}
	store->qari_scanned[qari_index] = 1;

	char path[1024];
	for(u32 surah = 0; surah < SURAH_COUNT; ++surah) {
		u32         key   = TrackKey(qari_index, surah);
		TrackEntry *entry = &store->entries[key];
		if(AtomicLoad(TrackStatePtr(store, entry)) != TRACK_REMOTE) {
			continue;
		}

		struct stat info;
		store_track_path(store, key, false, path, sizeof(path));
		if(stat(path, &info) == 0) {
			AtomicStore(&entry->bytes_total, (u64)info.st_size);
			AtomicStore(&entry->bytes_done, (u64)info.st_size);
			store_set_state(store, key, TRACK_DONE);
			continue;
		}

		store_track_path(store, key, true, path, sizeof(path));
		if(stat(path, &info) == 0) {
			AtomicStore(&entry->bytes_done, (u64)info.st_size);
			u8 expected = TRACK_REMOTE;
			AtomicCompareExchange(TrackStatePtr(store, entry), &expected, (u8)TRACK_PARTIAL);
		}
	}
}

// NOTE: one readdir per qari directory that exists instead of 20k stat()s. at startup this
// marks everything on disk, which is what the offline view lists.
internal void store_scan_disk(TrackStore *store)
{
	Catalog *catalog = store->catalog;
	char     path[1024];
	for(u32 qari = 0; qari < catalog->qari_count; ++qari) {
		String8 relative = catalog->qaris[qari].relative_path;
		snprintf(path, sizeof(path), Str8Fmt "/" Str8Fmt, Str8Arg(store->audio_dir), Str8Arg(relative));
		store->qari_scanned[qari] = 1;

		int dir_fd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
		if(dir_fd < 0) {
			continue;
		}
		DIR *dir = fdopendir(dir_fd);
		if(!dir) {
			close(dir_fd);
			continue;
		}

		struct dirent *item;
		while((item = readdir(dir))) {
			// "NNN.mp3" or "NNN.mp3.part"
			const char *name = item->d_name;
			if(!(name[0] >= '0' && name[0] <= '9' && name[1] >= '0' && name[1] <= '9' && name[2] >= '0' && name[2] <= '9')) {
				continue;
			}
			u32 surah   = (u32)((name[0] - '0') * 100 + (name[1] - '0') * 10 + (name[2] - '0'));
			b32 partial = strcmp(name + 3, ".mp3.part") == 0;
			if(surah < 1 || surah > SURAH_COUNT || (!partial && strcmp(name + 3, ".mp3") != 0)) {
				continue;
			}
			struct stat info;
			if(fstatat(dir_fd, name, &info, 0) != 0) {
				continue;
			}
			TrackEntry *entry = &store->entries[TrackKey(qari, surah - 1)];
			if(!partial) {
				AtomicStore(&entry->bytes_total, (u64)info.st_size);
				AtomicStore(&entry->bytes_done, (u64)info.st_size);
				store_set_state(store, TrackKey(qari, surah - 1), TRACK_DONE);
			} else if(AtomicLoad(TrackStatePtr(store, entry)) == TRACK_REMOTE) {
				AtomicStore(&entry->bytes_done, (u64)info.st_size);
				AtomicStore(TrackStatePtr(store, entry), (u32)TRACK_PARTIAL);
			}
		}
		closedir(dir);
	}
}

internal b32 store_on_disk(TrackStore *store, u32 key)
{
	return key < store->entry_count && AtomicLoadRelaxed(&store->states[key]) == TRACK_DONE;
}

internal u32 store_disk_count(TrackStore *store, u32 qari_index)
{
	return AtomicLoadRelaxed(&store->qari_done[qari_index]);
}

internal b32 store_delete(TrackStore *store, u32 key)
{
	TrackEntry *entry = store_entry(store, key);
	if(!entry) {
		return false;
	}
	u32 state = AtomicLoad(TrackStatePtr(store, entry));
	if(state == TRACK_QUEUED || state == TRACK_DOWNLOADING) {
		return false; // a worker owns it right now
	}
	char path[1024];
	store_track_path(store, key, false, path, sizeof(path));
	unlink(path);
	store_track_path(store, key, true, path, sizeof(path));
	unlink(path);
	store_set_state(store, key, TRACK_REMOTE);
	AtomicStore(&entry->bytes_done, (u64)0);
	AtomicStore(&entry->bytes_total, (u64)0);
	signal_notify(&store->progress);
	return true;
}

//- requests

internal b32 store_request(TrackStore *store, u32 key, b32 urgent)
{
	TrackEntry *entry = store_entry(store, key);
	if(!entry) {
		return false;
	}
	store_scan_qari(store, TrackQari(key));

	for(;;) {
		u32 state = AtomicLoad(TrackStatePtr(store, entry));
		switch(state) {
			case TRACK_DONE:
			case TRACK_DOWNLOADING: {
				return true;
			}
			case TRACK_QUEUED: {
				// NOTE: already in the bulk lane. pushing it again on the urgent lane is fine, the
				// worker that pops the second copy sees it is no longer QUEUED and skips it.
				if(urgent) {
					job_queue_push_front(&store->queue, key);
				}
				return true;
			}
			case TRACK_REMOTE:
			case TRACK_PARTIAL:
			case TRACK_FAILED: {
				u8 expected = (u8)state;
				if(AtomicCompareExchange(TrackStatePtr(store, entry), &expected, (u8)TRACK_QUEUED)) {
					AtomicStoreRelaxed(&entry->retries, 0u);
					b32 pushed = urgent ? job_queue_push_front(&store->queue, key) : job_queue_push_back(&store->queue, key);
					signal_notify(&store->progress);
					return pushed;
				}
				// lost a race with a worker, look again
			} break;
			default: return false;
		}
	}
}

internal u32 store_request_qari(TrackStore *store, u32 qari_index)
{
	u32 queued = 0;
	store_scan_qari(store, qari_index);
	for(u32 surah = 0; surah < SURAH_COUNT; ++surah) {
		u32 key = TrackKey(qari_index, surah);
		u32 state = AtomicLoad(&store->states[key]);
		if(state != TRACK_DONE && store_request(store, key, false)) {
			++queued;
		}
	}
	return queued;
}

//- worker

typedef struct DownloadContext DownloadContext;
struct DownloadContext {
	DownloadWorker *worker;
	TrackEntry     *entry;
	CURL           *curl;
	int             fd;
	u64             resume_from;
	b32             checked_headers;
	b32             truncated;
};

internal void store_notify(TrackStore *store, DownloadWorker *worker, b32 force)
{
	signal_notify(&store->progress);
	if(store->quiet) {
		return;
	}
	// NOTE: the decoder gets every chunk, the ui only ~15 times a second per worker
	u64 now = time_now_ns();
	if(force || now - worker->last_wake_ns > 66000000ull) {
		worker->last_wake_ns = now;
		wake_main();
	}
}

internal size_t store_download_write(char *pointer, size_t size, size_t count, void *user)
{
	DownloadContext *context = (DownloadContext *)user;
	TrackEntry      *entry   = context->entry;
	u64              bytes   = (u64)size * count;

	if(!context->checked_headers) {
		context->checked_headers = true;

		long status = 0;
		curl_easy_getinfo(context->curl, CURLINFO_RESPONSE_CODE, &status);
		if(status == 200 && context->resume_from > 0) {
			// NOTE: server ignored our range request and sent the whole file, start over
			if(ftruncate(context->fd, 0) != 0) {
				return 0;
			}
			lseek(context->fd, 0, SEEK_SET);
			context->resume_from = 0;
			AtomicStore(&entry->bytes_done, (u64)0);
		}

		curl_off_t remaining = -1;
		curl_easy_getinfo(context->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &remaining);
		if(remaining > 0) {
			AtomicStore(&entry->bytes_total, context->resume_from + (u64)remaining);
		}
	}

	u64 written = 0;
	while(written < bytes) {
		ssize_t result = write(context->fd, pointer + written, bytes - written);
		if(result < 0) {
			if(errno == EINTR) continue;
			return 0; // aborts the transfer
		}
		written += (u64)result;
	}

	// NOTE: release store: the decoder reads bytes_done then pread()s up to it
	AtomicStore(&entry->bytes_done, AtomicLoadRelaxed(&entry->bytes_done) + bytes);
	AtomicAddRelaxed(&context->worker->store->bytes_downloaded, bytes);
	store_notify(context->worker->store, context->worker, false);
	return bytes;
}

internal void store_download(DownloadWorker *worker, CURL *curl, u32 key)
{
	TrackStore *store = worker->store;
	TrackEntry *entry = &store->entries[key];

	char final_path[1024];
	char part_path[1024];
	store_track_path(store, key, false, final_path, sizeof(final_path));
	store_track_path(store, key, true, part_path, sizeof(part_path));

	// NOTE: make sure <audio>/<qari>/ exists
	{
		char directory[1024];
		MemCpy(directory, final_path, sizeof(directory));
		char *slash = strrchr(directory, '/');
		if(slash) {
			*slash = 0;
			make_directories(directory);
		}
	}

	int fd = open(part_path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
	if(fd < 0) {
		Log("cannot open %s: %s", part_path, strerror(errno));
		AtomicStore(TrackStatePtr(store, entry), (u32)TRACK_FAILED);
		return;
	}

	struct stat info = {};
	fstat(fd, &info);

	DownloadContext context = {};
	context.worker          = worker;
	context.entry           = entry;
	context.curl            = curl;
	context.fd              = fd;
	context.resume_from     = (u64)info.st_size;
	AtomicStore(&entry->bytes_done, context.resume_from);

	char url[1024];
	Qari *qari = &store->catalog->qaris[TrackQari(key)];
	snprintf(url, sizeof(url), CATALOG_AUDIO_BASE Str8Fmt "%03u.mp3", Str8Arg(qari->relative_path), TrackSurah(key) + 1);

	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, store_download_write);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &context);
	curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, (curl_off_t)context.resume_from);

	CURLcode result = curl_easy_perform(curl);
	long     status = 0;
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
	AtomicStoreRelaxed(&entry->http_status, (u32)status);
	close(fd);

	// NOTE: 416 on resume means the .part was already the complete file
	b32 complete = (result == CURLE_OK) || (status == 416 && context.resume_from > 0);

	if(complete) {
		if(rename(part_path, final_path) == 0) {
			struct stat final_info = {};
			stat(final_path, &final_info);
			AtomicStore(&entry->bytes_total, (u64)final_info.st_size);
			AtomicStore(&entry->bytes_done, (u64)final_info.st_size);
			store_set_state(store, key, TRACK_DONE);
			AtomicAdd(&store->completed, 1u);
		} else {
			AtomicStore(TrackStatePtr(store, entry), (u32)TRACK_FAILED);
			AtomicAdd(&store->failed, 1u);
		}
	} else {
		b32 http_error = status >= 400 && status < 500;
		u32 retries    = AtomicAdd(&entry->retries, 1u);
		Log("download %s failed: %s (http %ld, try %u)", url, curl_easy_strerror(result), status, retries);

		if(!http_error && retries < 4) {
			// NOTE: network hiccup, keep the .part and go to the back of the line
			AtomicStore(TrackStatePtr(store, entry), (u32)TRACK_QUEUED);
			sleep_ns(500000000ull * retries);
			job_queue_push_back(&store->queue, key);
		} else {
			if(http_error) {
				unlink(part_path); // a 404 page isn't audio
				AtomicStore(&entry->bytes_done, (u64)0);
			}
			AtomicStore(TrackStatePtr(store, entry), (u32)TRACK_FAILED);
			AtomicAdd(&store->failed, 1u);
		}
	}

	store_notify(store, worker, true);
}

internal void store_worker_main(void *param)
{
	DownloadWorker *worker = (DownloadWorker *)param;
	TrackStore     *store  = worker->store;

	char name[16];
	snprintf(name, sizeof(name), "download %u", worker->index);
	thread_set_name(str8(name));
	profile_thread_register(name);

	// NOTE: one easy handle per worker for its whole life, so keep-alive connections and the
	// tls session get reused across every file this worker pulls
	CURL *curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15L);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1024L);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 30L);
	curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, 256L * 1024L);
	curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2TLS);
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "mp3_player/1.0");

	u32 key = 0;
	while(job_queue_pop(&store->queue, &key)) {
		TrackEntry *entry    = &store->entries[key];
		u8          expected = TRACK_QUEUED;
		if(!AtomicCompareExchange(TrackStatePtr(store, entry), &expected, (u8)TRACK_DOWNLOADING)) {
			continue; // duplicate from the urgent lane, someone already has it
		}

		AtomicStoreRelaxed(&worker->current_key, key);
		AtomicAdd(&store->active, 1u);
		store_download(worker, curl, key);
		AtomicAdd(&store->active, (u32)-1);
		AtomicStoreRelaxed(&worker->current_key, TRACK_NONE);
	}

	curl_easy_cleanup(curl);
}

internal void store_start_workers(Arena *arena, TrackStore *store, u32 worker_count)
{
	store->worker_count = Clamp(worker_count, 1u, (u32)STORE_MAX_WORKERS);
	for(u32 index = 0; index < store->worker_count; ++index) {
		DownloadWorker *worker = &store->workers[index];
		worker->store          = store;
		worker->index          = index;
		worker->current_key    = TRACK_NONE;
		worker->thread         = thread_launch(arena, store_worker_main, worker);
	}
}

internal void store_stop_workers(TrackStore *store)
{
	job_queue_quit(&store->queue);
	for(u32 index = 0; index < store->worker_count; ++index) {
		// NOTE: a worker can be mid transfer, detach instead of blocking quit on the network
		thread_detach(store->workers[index].thread);
	}
}