chirkle 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +32 -24
  2. package/bin/release/darwin-amd64/chirkle-server +2 -2
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +0 -0
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +2 -1
  7. package/pb_hooks/lib/account.js +541 -6
  8. package/pb_hooks/lib/collections.js +4 -4
  9. package/pb_hooks/lib/dms.js +1 -1
  10. package/pb_hooks/lib/inbox.js +1 -1
  11. package/pb_hooks/lib/invites.js +266 -0
  12. package/pb_hooks/lib/messages.js +11 -2
  13. package/pb_hooks/lib/moderation.js +1 -1
  14. package/pb_hooks/lib/retention.js +3 -0
  15. package/pb_hooks/lib/site.js +1 -1
  16. package/pb_hooks/lib/users.js +38 -10
  17. package/pb_hooks/main.pb.js +26 -1
  18. package/pb_hooks/telegram/api.js +64 -12
  19. package/pb_hooks/telegram/inbound.js +106 -15
  20. package/pb_hooks/telegram/outbound.js +63 -37
  21. package/pb_hooks/telegram/worker.js +59 -15
  22. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  23. package/pb_migrations/1760000053_account_jobs.js +45 -0
  24. package/pb_migrations/1760000054_room_invites.js +39 -0
  25. package/pb_migrations/1760000055_invite_barred.js +16 -0
  26. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  27. package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
  28. package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
  29. package/pb_public/assets/access-UK3L54NR.js +2 -0
  30. package/pb_public/assets/access-UK3L54NR.js.map +7 -0
  31. package/pb_public/assets/account-CT2BVMAX.css +2 -0
  32. package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
  33. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  34. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  35. package/pb_public/assets/app-HB3NZHQ2.js +3 -0
  36. package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
  37. package/pb_public/assets/app-XJ73EU5O.css +2 -0
  38. package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
  39. package/pb_public/assets/chunk-AG73QNUN.js +2 -0
  40. package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
  41. package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
  42. package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
  43. package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
  44. package/pb_public/assets/{chunk-PWNJABVI.js.map → chunk-N2OFGBCZ.js.map} +4 -4
  45. package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
  46. package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
  47. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  48. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  49. package/pb_public/assets/chunk-WR25F7FU.js +2 -0
  50. package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
  51. package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
  52. package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
  53. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  54. package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
  55. package/pb_public/assets/login-TK6K4WGB.js +2 -0
  56. package/pb_public/assets/{login-ECFBJP6Q.js.map → login-TK6K4WGB.js.map} +1 -1
  57. package/pb_public/assets/profile-3R6S5QYS.js +2 -0
  58. package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
  59. package/pb_public/assets/stats-GTO2H6PG.js +2 -0
  60. package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
  61. package/pb_public/index.html +7 -5
  62. package/pb_public/stats.html +1 -1
  63. package/scripts/service.mjs +201 -0
  64. package/scripts/start.mjs +7 -1
  65. package/pb_public/assets/access-LHPD2EHG.js +0 -2
  66. package/pb_public/assets/access-LHPD2EHG.js.map +0 -7
  67. package/pb_public/assets/app-6ETOTHXQ.js +0 -3
  68. package/pb_public/assets/app-6ETOTHXQ.js.map +0 -7
  69. package/pb_public/assets/app-ZGHECF33.css +0 -2
  70. package/pb_public/assets/app-ZGHECF33.css.map +0 -7
  71. package/pb_public/assets/chunk-GXMWOXBX.js +0 -2
  72. package/pb_public/assets/chunk-GXMWOXBX.js.map +0 -7
  73. package/pb_public/assets/chunk-IFQGGTSP.js +0 -2
  74. package/pb_public/assets/chunk-IFQGGTSP.js.map +0 -7
  75. package/pb_public/assets/chunk-PWNJABVI.js +0 -2
  76. package/pb_public/assets/login-ECFBJP6Q.js +0 -2
  77. package/pb_public/assets/profile-NQQLAEDT.js +0 -2
  78. package/pb_public/assets/profile-NQQLAEDT.js.map +0 -7
  79. package/pb_public/assets/stats-ARDU576A.js +0 -2
  80. package/pb_public/assets/stats-ARDU576A.js.map +0 -7
@@ -22,6 +22,13 @@ function config() {
22
22
  * message_reaction only where the bot is an admin. */
23
23
  const UPDATES = ["message", "edited_message", "channel_post", "edited_channel_post", "my_chat_member", "message_reaction"];
24
24
 
25
+ /**
26
+ * What a failed request's error says when it never reached Telegram: no connection was made (no address, refused,
27
+ * unreachable, the connection or its TLS handshake failed or timed out). Anything else (no answer in time, the
28
+ * connection lost or reset once made) may have reached it: a send may have been made.
29
+ */
30
+ const UNSENT = /dial tcp|no such host|connection refused|network is unreachable|no route to host|tls handshake|tls: /i;
31
+
25
32
  /** A refused or failed call. `retryAfter`: seconds Telegram asks to wait (429). `status` 0: no answer. */
26
33
  class TelegramError extends Error {
27
34
  /**
@@ -40,6 +47,14 @@ class TelegramError extends Error {
40
47
  get transient() {
41
48
  return this.status === 0 || this.status === 429 || this.status >= 500;
42
49
  }
50
+
51
+ /**
52
+ * It may have done what it asked though it failed: no answer came (a timeout, a connection lost or reset), after
53
+ * the request may have reached Telegram. Not when Telegram answered (it refused), nor when no connection was made.
54
+ */
55
+ get maybeDone() {
56
+ return this.status === 0 && !UNSENT.test(this.message);
57
+ }
43
58
  }
44
59
 
45
60
  /**
@@ -49,13 +64,20 @@ class TelegramError extends Error {
49
64
  */
50
65
  const asTelegram = (err) => (err instanceof TelegramError ? err : null);
51
66
 
67
+ /**
68
+ * Seconds an upload or download of `bytes` may take: enough at 200 KB/s, from 30 s up to 300 s. A connection that
69
+ * stops answering fails within that, not after a fixed 5 minutes, which held the worker past its lock (§26.7).
70
+ * @param {number} bytes
71
+ */
72
+ const transferTimeout = (bytes) => Math.min(300, 30 + Math.ceil(bytes / 200_000));
73
+
52
74
  /**
53
75
  * Call a Bot API method. Files (filesystem.File by field name) go as multipart, the other params as fields (objects
54
76
  * as JSON); without files the params are a JSON body.
55
77
  * @param {string} method
56
78
  * @param {Record<string, unknown>} [params]
57
79
  * @param {Record<string, any>} [files]
58
- * @param {number} [timeout] seconds
80
+ * @param {number} [timeout] seconds (with files: the upload's, transferTimeout)
59
81
  * @returns {any} the method's result
60
82
  */
61
83
  function call(method, params = {}, files, timeout = 30) {
@@ -71,7 +93,7 @@ function call(method, params = {}, files, timeout = 30) {
71
93
  if (v !== undefined) form.append(k, typeof v === "string" ? v : JSON.stringify(v));
72
94
  }
73
95
  for (const [k, f] of Object.entries(files)) form.append(k, f);
74
- res = $http.send({ url, method: "POST", body: form, timeout: Math.max(timeout, 300) });
96
+ res = $http.send({ url, method: "POST", body: form, timeout });
75
97
  } else {
76
98
  res = $http.send({ url, method: "POST", body: JSON.stringify(params), headers: { "content-type": "application/json" }, timeout });
77
99
  }
@@ -107,23 +129,53 @@ function storedName(name, path) {
107
129
  }
108
130
 
109
131
  /**
110
- * Download a file the bot can see (at most 20 MB, the Bot API's limit), named `name`.
132
+ * `fn` again at once, up to `tries` times in all, while it fails for now: for what may run twice (getFile, a
133
+ * download). A failure that has to wait longer (429 with retry_after over 5 s) is left to the caller.
134
+ * @template T
135
+ * @param {() => T} fn
136
+ * @param {number} [tries]
137
+ * @returns {T}
138
+ */
139
+ function retrying(fn, tries = 2) {
140
+ for (let i = 1; ; i++) {
141
+ try {
142
+ return fn();
143
+ } catch (err) {
144
+ const tg = asTelegram(err);
145
+ if (!tg?.transient || i >= tries || tg.retryAfter > 5) throw err;
146
+ sleep(tg.retryAfter ? tg.retryAfter * 1000 : 500 * i);
147
+ }
148
+ }
149
+ }
150
+
151
+ /** getFile's timeout: a small call, which a connection that answers does at once. */
152
+ const GET_FILE_TIMEOUT = 10;
153
+
154
+ /**
155
+ * Download a file the bot can see (at most 20 MB, the Bot API's limit), named `name`. A failure that may pass is
156
+ * tried again at once: a connection that drops now and then fails one request, rarely two (§26.4).
111
157
  * @param {string} fileId
112
158
  * @param {string} name
159
+ * @param {number} [size] its size, when Telegram said: how long the download may take
113
160
  */
114
- function download(fileId, name) {
161
+ function download(fileId, name, size = 0) {
115
162
  const { token, base } = config();
116
- const info = call("getFile", { file_id: fileId });
163
+ const info = retrying(() => call("getFile", { file_id: fileId }, undefined, GET_FILE_TIMEOUT));
117
164
  if (!info?.file_path) throw new TelegramError(400, "getFile: no file_path");
118
- let file;
119
- try {
120
- file = $filesystem.fileFromURL(`${base}/file/bot${token}/${info.file_path}`, 120);
121
- } catch (err) {
122
- throw new TelegramError(0, `download: ${String(err).replace(token, "<token>")}`);
123
- }
165
+ const timeout = transferTimeout(size || info.file_size || 20 * 1024 * 1024);
166
+ const file = retrying(() => {
167
+ try {
168
+ return $filesystem.fileFromURL(`${base}/file/bot${token}/${info.file_path}`, timeout);
169
+ } catch (err) {
170
+ const text = String(err).replace(token, "<token>");
171
+ // "failed to download url … (404)": Telegram answered.
172
+ const status = Number((/\((\d{3})\)\s*$/.exec(text) || ["", "0"])[1]);
173
+ throw new TelegramError(status, `download: ${text}`);
174
+ }
175
+ });
124
176
  file.originalName = name;
125
177
  file.name = storedName(name, info.file_path);
126
178
  return file;
127
179
  }
128
180
 
129
- module.exports = { config, call, download, asTelegram, TelegramError, UPDATES };
181
+ module.exports = { config, call, download, asTelegram, TelegramError, transferTimeout, UPDATES };
@@ -3,7 +3,7 @@
3
3
  // becomes a chat message of its sender's stand-in, with its files; an album (sent as one update per item) becomes one
4
4
  // message once all of it is in; an edit edits it. Telegram doesn't tell bots about deleted messages.
5
5
 
6
- const { call, config, download } = require(`${__hooks}/telegram/api.js`);
6
+ const { asTelegram, call, config, download } = require(`${__hooks}/telegram/api.js`);
7
7
  const { personOf } = require(`${__hooks}/telegram/people.js`);
8
8
  const { activeLink, ensureLink, linkedRoom, linkOfChat, moveLink, tellLinkChange } = require(`${__hooks}/telegram/links.js`);
9
9
  const { richText } = require(`${__hooks}/telegram/rich.js`);
@@ -79,10 +79,10 @@ function quoteLines(msg, known) {
79
79
  * A Telegram message's text (its caption, or a rich message's blocks as text), its files (that can be brought over),
80
80
  * and lines for what can't be: files over the download limit, and things that aren't files (a location, a poll…).
81
81
  * @param {any} msg
82
- * @returns {{ text: string, files: { id: string, name: string }[], notes: string[] }}
82
+ * @returns {{ text: string, files: { id: string, name: string, size: number }[], notes: string[] }}
83
83
  */
84
84
  function partsOf(msg) {
85
- /** @type {{ id: string, name: string }[]} */
85
+ /** @type {{ id: string, name: string, size: number }[]} */
86
86
  const files = [];
87
87
  /** @type {string[]} */
88
88
  const notes = [];
@@ -93,7 +93,7 @@ function partsOf(msg) {
93
93
  */
94
94
  const add = (f, name) => {
95
95
  if (f.file_size && f.file_size > MAX_FILE) notes.push(`[${name}, ${mb(f.file_size)}: too large to bring over from Telegram]`);
96
- else files.push({ id: f.file_id, name });
96
+ else files.push({ id: f.file_id, name, size: f.file_size || 0 });
97
97
  };
98
98
  if (msg.photo?.length) add(msg.photo[msg.photo.length - 1], `photo_${n}.jpg`);
99
99
  if (msg.video) add(msg.video, msg.video.file_name || `video_${n}.mp4`);
@@ -278,17 +278,26 @@ function ensureMember(app, room, userId) {
278
278
 
279
279
  /**
280
280
  * Bring Telegram messages over as one chat message: one message, or the items of an album.
281
+ *
282
+ * A file that fails to download for now (no answer from Telegram) doesn't become "couldn't be brought over": `live`
283
+ * (as they come) the messages are queued for the worker (a `fetch`, §26.4) and come over once their files do; `retry`
284
+ * (the worker's) the failure is thrown, for the worker to try again later; `last` (its last try) what still fails
285
+ * says so in the text, as one Telegram refuses does.
281
286
  * @param {core.App} app
282
287
  * @param {core.Record} link tg_links
283
288
  * @param {core.Record} room
284
289
  * @param {any[]} msgs
290
+ * @param {"live" | "retry" | "last"} [mode]
285
291
  */
286
- function bringOver(app, link, room, msgs) {
292
+ function bringOver(app, link, room, msgs, mode = "live") {
287
293
  const chatId = link.getString("chat_id");
288
- // Delivered twice (a webhook retry): brought over already, or an album item queued twice, which would fail the save
289
- // of the whole album on the unique (chat_id, tg_message_id) (QA BUG-147).
294
+ // Delivered twice (a webhook retry): brought over already, waiting for its files, or an album item queued twice,
295
+ // which would fail the save of the whole album on the unique (chat_id, tg_message_id) (QA BUG-147).
290
296
  const seen = new Set();
291
- msgs = msgs.filter((m) => !seen.has(m.message_id) && seen.add(m.message_id) && !mapped(app, chatId, m.message_id, m.date));
297
+ const waiting = mode === "live" ? fetching(app, chatId) : new Set();
298
+ msgs = msgs.filter(
299
+ (m) => !seen.has(m.message_id) && seen.add(m.message_id) && !waiting.has(m.message_id) && !mapped(app, chatId, m.message_id, m.date),
300
+ );
292
301
  if (!msgs.length) return;
293
302
  msgs.sort((a, b) => a.message_id - b.message_id);
294
303
  const first = msgs[0];
@@ -297,9 +306,6 @@ function bringOver(app, link, room, msgs) {
297
306
  // A service message (a new group photo, a timer, a topic…) has nothing to show: it makes no stand-in, and none joins
298
307
  // a private room for it (QA BUG-88).
299
308
  if (!notes.length && !parts.some((p) => p.files.length) && !parts.some((p) => p.text.trim())) return;
300
- const author = personOf(app, first);
301
- ensureMember(app, room, author.id);
302
-
303
309
  /** @type {any[]} */
304
310
  const files = [];
305
311
  for (const f of parts.flatMap((p) => p.files)) {
@@ -308,12 +314,17 @@ function bringOver(app, link, room, msgs) {
308
314
  continue;
309
315
  }
310
316
  try {
311
- files.push(download(f.id, f.name));
317
+ files.push(download(f.id, f.name, f.size));
312
318
  } catch (err) {
313
- app.logger().warn("telegram: download", "chat", chatId, "error", String(err));
319
+ const later = mode !== "last" && !!asTelegram(err)?.transient;
320
+ app.logger().warn("telegram: download", "chat", chatId, "message", first.message_id, "later", later, "error", String(err));
321
+ if (later && mode === "retry") throw err;
322
+ if (later && queueFetch(app, chatId, msgs, String(err))) return;
314
323
  notes.push(`[${f.name}: couldn't be brought over from Telegram]`);
315
324
  }
316
325
  }
326
+ const author = personOf(app, first);
327
+ ensureMember(app, room, author.id);
317
328
  const reply = first.reply_to_message ? mapped(app, chatId, first.reply_to_message.message_id, first.reply_to_message.date) : null;
318
329
  const known = !!reply && reply.getString("room") === room.id && !reply.getBool("deleted");
319
330
  const textOf = (/** @type {boolean} */ withReply) =>
@@ -361,7 +372,8 @@ function editOver(app, msg) {
361
372
  const chatId = String(msg.chat.id);
362
373
  const rows = partsMapped(app, chatId, msg.message_id, msg.date);
363
374
  const rec = rows[0]?.getInt("part") === 0 ? findMessage(app, rows[0].getString("message")) : null;
364
- if (!rec || rec.getBool("deleted") || rec.getString("forwarded_from")) return;
375
+ if (!rec) return editWaiting(app, chatId, msg);
376
+ if (rec.getBool("deleted") || rec.getString("forwarded_from")) return;
365
377
  const quoted = quoteLines(msg, !!rec.getString("reply_to"));
366
378
  const { text, notes } = partsOf(msg);
367
379
  const lines = [forwardLine(msg), ...quoted, text, ...notes].filter(Boolean);
@@ -417,6 +429,85 @@ function queueAlbumItem(app, msg) {
417
429
  app.save(row);
418
430
  }
419
431
 
432
+ /**
433
+ * The queued fetches of a chat (Telegram messages waiting for their files, §26.4).
434
+ * @param {core.App} app
435
+ * @param {string} chatId
436
+ */
437
+ const fetchesOf = (app, chatId) =>
438
+ app.findRecordsByFilter("tg_queue", "op = 'fetch' && chat_id = {:chat}", "created", 0, 0, { chat: chatId }).filter((r) => !!r);
439
+
440
+ /** @param {core.Record} row a fetch */
441
+ const fetchMessages = (row) => /** @type {any[]} */ (JSON.parse(row.getString("payload") || "null")?.msgs || []);
442
+
443
+ /**
444
+ * The ids of a chat's Telegram messages waiting for their files.
445
+ * @param {core.App} app
446
+ * @param {string} chatId
447
+ */
448
+ function fetching(app, chatId) {
449
+ return new Set(fetchesOf(app, chatId).flatMap((r) => fetchMessages(r).map((m) => m.message_id)));
450
+ }
451
+
452
+ /**
453
+ * Queue Telegram messages whose files couldn't be downloaded for now: the worker brings them over later (fetchOver).
454
+ * @param {core.App} app
455
+ * @param {string} chatId
456
+ * @param {any[]} msgs
457
+ * @param {string} error
458
+ * @returns {boolean} queued
459
+ */
460
+ function queueFetch(app, chatId, msgs, error) {
461
+ try {
462
+ const row = new Record(app.findCollectionByNameOrId("tg_queue"));
463
+ row.set("op", "fetch");
464
+ row.set("chat_id", chatId);
465
+ row.set("payload", { msgs });
466
+ row.set("tries", 1);
467
+ row.set("next_at", new DateTime(new Date(Date.now() + 2000).toISOString()));
468
+ row.set("error", error.slice(0, 1000));
469
+ app.save(row);
470
+ return true;
471
+ } catch (err) {
472
+ // Too big to queue (a payload over 64 KB): it comes over now, saying what couldn't.
473
+ app.logger().error("telegram: fetch", "chat", chatId, "error", String(err));
474
+ return false;
475
+ }
476
+ }
477
+
478
+ /**
479
+ * An edit of a Telegram message still waiting for its files: it comes over as edited.
480
+ * @param {core.App} app
481
+ * @param {string} chatId
482
+ * @param {any} msg
483
+ */
484
+ function editWaiting(app, chatId, msg) {
485
+ const has = (/** @type {core.Record} */ row) => fetchMessages(row).some((m) => m.message_id === msg.message_id);
486
+ if (!fetchesOf(app, chatId).some(has)) return;
487
+ // Read again in a transaction: the worker may be saving the row (its tries) meanwhile.
488
+ app.runInTransaction((tx) => {
489
+ for (const row of fetchesOf(tx, chatId).filter(has)) {
490
+ row.set("payload", { msgs: fetchMessages(row).map((m) => (m.message_id === msg.message_id ? msg : m)) });
491
+ tx.save(row);
492
+ }
493
+ });
494
+ }
495
+
496
+ /**
497
+ * The worker's try at a queued fetch: its messages come over with their files, or (`last`) with what still fails
498
+ * said in their text. Fails, for the worker to try again, while a file fails to download for now.
499
+ * @param {core.App} app
500
+ * @param {core.Record} row
501
+ * @param {boolean} last
502
+ */
503
+ function fetchOver(app, row, last) {
504
+ const chatId = row.getString("chat_id");
505
+ const link = linkOfChat(app, chatId);
506
+ const room = link && activeLink(app, link);
507
+ if (!link || !room) return;
508
+ bringOver(app, link, room, fetchMessages(row), last ? "last" : "retry");
509
+ }
510
+
420
511
  /**
421
512
  * Take an album's queued items, so only one caller brings it over.
422
513
  * @param {core.App} app
@@ -586,4 +677,4 @@ function webhook(e) {
586
677
  return e.json(200, { ok: true });
587
678
  }
588
679
 
589
- module.exports = { webhook, handleUpdate, flushAlbums, mapped };
680
+ module.exports = { webhook, handleUpdate, flushAlbums, fetchOver, mapped };
@@ -4,7 +4,7 @@
4
4
  // refuses for now (it is down, or asks to slow down) is retried in order.
5
5
 
6
6
  const { roomName, sourceName } = require(`${__hooks}/lib/anonymous.js`);
7
- const { asTelegram, call } = require(`${__hooks}/telegram/api.js`);
7
+ const { asTelegram, call, transferTimeout } = require(`${__hooks}/telegram/api.js`);
8
8
  const { linkOfChat, linksOfRoom } = require(`${__hooks}/telegram/links.js`);
9
9
 
10
10
  /** Telegram's limits: a caption's length, and the largest photo it takes as a photo (bigger ones go as files). */
@@ -237,7 +237,7 @@ function filesOf(app, fsys, source) {
237
237
  const kind = sticker ? "sticker" : PHOTO_EXT.has(ext) && size <= MAX_PHOTO ? "photo" : VIDEO_EXT.has(ext) ? "video" : "document";
238
238
  const file = fsys.getReuploadableFile(key, true);
239
239
  file.name = names[name] || name.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
240
- return { kind, file };
240
+ return { kind, file, size };
241
241
  });
242
242
  }
243
243
 
@@ -250,23 +250,26 @@ const SEND = /** @type {Record<string, string>} */ ({
250
250
 
251
251
  /**
252
252
  * Send a message to a group: its text (with its files as their caption when it fits), its files as one or two
253
- * albums, as a reply when the message it answers is there.
253
+ * albums, as a reply when the message it answers is there. Those are its steps, sent in turn: `done` of them were
254
+ * sent by an earlier try, which failed at the next one, and `sent(n)` is told after each (the worker keeps it), so a
255
+ * try again sends the rest, neither the steps already in the group again nor nothing more (§26.7).
254
256
  * @param {core.App} app
255
257
  * @param {string} messageId
256
258
  * @param {string} chatId
259
+ * @param {number} [done]
260
+ * @param {(n: number) => void} [sent]
257
261
  */
258
- function send(app, messageId, chatId) {
262
+ function send(app, messageId, chatId, done = 0, sent = () => {}) {
259
263
  const msg = findMessage(app, messageId);
260
264
  if (!msg || msg.getBool("deleted")) return;
261
265
  const link = linkOfChat(app, chatId);
262
266
  if (!link?.getBool("enabled") || link.getString("room") !== msg.getString("room")) return;
263
- // Came from this group, or already sent (a retry after the worker stopped halfway).
264
- if (mappings(app, messageId, chatId).length) return;
267
+ // Came from this group, or already sent (a retry after the worker stopped halfway, before it kept the steps).
268
+ if (!done && mappings(app, messageId, chatId).length) return;
265
269
 
266
270
  const { html, plain, source } = contentOf(app, msg, link.getBool("anonymous"));
267
271
  const replyTo = msg.getString("reply_to") ? mappings(app, msg.getString("reply_to"), chatId)[0] : null;
268
- /** @type {any} */
269
- let reply = replyTo ? { reply_parameters: { message_id: replyTo.getInt("tg_message_id"), allow_sending_without_reply: true } } : {};
272
+ const reply = replyTo ? { reply_parameters: { message_id: replyTo.getInt("tg_message_id"), allow_sending_without_reply: true } } : {};
270
273
 
271
274
  const fsys = app.newFilesystem();
272
275
  try {
@@ -274,44 +277,67 @@ function send(app, messageId, chatId) {
274
277
  const groups = [files.filter((f) => f.kind !== "document"), files.filter((f) => f.kind === "document")].filter((g) => g.length);
275
278
  // A sticker takes no caption: its text goes before it.
276
279
  const captioned = groups.length && files[0].kind !== "sticker";
277
- let caption = captioned && [...plain].length <= MAX_CAPTION ? { caption: html, parse_mode: "HTML" } : null;
280
+ const caption = captioned && [...plain].length <= MAX_CAPTION ? { caption: html, parse_mode: "HTML" } : null;
281
+ /** @type {((reply: Record<string, unknown>) => void)[]} */
282
+ const steps = [];
278
283
  // No text goes alone when there is none: an anonymous link's sticker, or a forward of a deleted message.
279
284
  if (!caption && html) {
280
- remember(app, messageId, chatId, call("sendMessage", { chat_id: chatId, text: html, parse_mode: "HTML", ...reply }), "text");
281
- reply = {};
285
+ steps.push((r) =>
286
+ remember(app, messageId, chatId, call("sendMessage", { chat_id: chatId, text: html, parse_mode: "HTML", ...r }), "text"),
287
+ );
282
288
  }
283
- for (const group of groups) {
284
- if (group.length === 1) {
285
- const f = group[0];
286
- const sent = call(
287
- SEND[f.kind],
288
- { chat_id: chatId, ...(f.kind === "video" ? STREAM : {}), ...(caption || {}), ...reply },
289
- { [f.kind]: f.file },
290
- );
291
- remember(app, messageId, chatId, sent, caption ? "caption" : "media");
292
- } else {
293
- /** @type {Record<string, any>} */
294
- const attach = {};
295
- const media = group.map((f, i) => {
296
- attach[`file${i}`] = f.file;
297
- return {
298
- type: f.kind,
299
- media: `attach://file${i}`,
300
- ...(f.kind === "video" ? STREAM : {}),
301
- ...(i === 0 && caption ? caption : {}),
302
- };
303
- });
304
- const sent = call("sendMediaGroup", { chat_id: chatId, media, ...reply }, attach);
305
- for (let i = 0; i < sent.length; i++) remember(app, messageId, chatId, sent[i], i === 0 && caption ? "caption" : "media");
306
- }
307
- caption = null;
308
- reply = {};
289
+ steps.push(
290
+ ...groups.map(
291
+ (group, g) => (/** @type {Record<string, unknown>} */ r) => sendGroup(app, messageId, chatId, group, g === 0 ? caption : null, r),
292
+ ),
293
+ );
294
+ // The first step answers what it replies to, the rest follow it.
295
+ for (let i = done; i < steps.length; i++) {
296
+ steps[i](i === 0 ? reply : {});
297
+ if (i + 1 < steps.length) sent(i + 1);
309
298
  }
310
299
  } finally {
311
300
  fsys.close();
312
301
  }
313
302
  }
314
303
 
304
+ /**
305
+ * One album of a message (or its one file), with the caption on its first item.
306
+ * @param {core.App} app
307
+ * @param {string} messageId
308
+ * @param {string} chatId
309
+ * @param {{ kind: string, file: any, size: number }[]} group
310
+ * @param {Record<string, unknown> | null} caption
311
+ * @param {Record<string, unknown>} reply
312
+ */
313
+ function sendGroup(app, messageId, chatId, group, caption, reply) {
314
+ const timeout = transferTimeout(group.reduce((n, f) => n + f.size, 0));
315
+ if (group.length === 1) {
316
+ const f = group[0];
317
+ const sent = call(
318
+ SEND[f.kind],
319
+ { chat_id: chatId, ...(f.kind === "video" ? STREAM : {}), ...(caption || {}), ...reply },
320
+ { [f.kind]: f.file },
321
+ timeout,
322
+ );
323
+ remember(app, messageId, chatId, sent, caption ? "caption" : "media");
324
+ return;
325
+ }
326
+ /** @type {Record<string, any>} */
327
+ const attach = {};
328
+ const media = group.map((f, i) => {
329
+ attach[`file${i}`] = f.file;
330
+ return {
331
+ type: f.kind,
332
+ media: `attach://file${i}`,
333
+ ...(f.kind === "video" ? STREAM : {}),
334
+ ...(i === 0 && caption ? caption : {}),
335
+ };
336
+ });
337
+ const sent = call("sendMediaGroup", { chat_id: chatId, media, ...reply }, attach, timeout);
338
+ for (let i = 0; i < sent.length; i++) remember(app, messageId, chatId, sent[i], i === 0 && caption ? "caption" : "media");
339
+ }
340
+
315
341
  /**
316
342
  * Pass an edit on: the Telegram messages that hold the text (sent from here) get the new one.
317
343
  * @param {core.App} app
@@ -5,7 +5,7 @@
5
5
  // POST /api/telegram/tick runs one pass at once (tests, or an admin who doesn't want to wait).
6
6
 
7
7
  const { asTelegram, call, config, UPDATES } = require(`${__hooks}/telegram/api.js`);
8
- const { flushAlbums, handleUpdate } = require(`${__hooks}/telegram/inbound.js`);
8
+ const { fetchOver, flushAlbums, handleUpdate } = require(`${__hooks}/telegram/inbound.js`);
9
9
  const { edit, remove, send } = require(`${__hooks}/telegram/outbound.js`);
10
10
 
11
11
  const LOCK = "telegram.worker";
@@ -20,6 +20,11 @@ const STALE_MS = 90_000;
20
20
  const CLAIM_MS = 10 * 60_000;
21
21
  /** How many times a send that failed for now is tried before it is dropped. */
22
22
  const MAX_TRIES = 8;
23
+ /**
24
+ * How many times a send is tried again after a failure that may have sent it (no answer once the request may have
25
+ * reached Telegram, api.js maybeDone): each such try may post it twice, so it gets one, not MAX_TRIES (§26.7).
26
+ */
27
+ const MAX_UNSURE = 1;
23
28
  /** Queue rows looked at in one pass. */
24
29
  const BATCH = 50;
25
30
 
@@ -65,6 +70,32 @@ function poll(app, timeout) {
65
70
  }
66
71
  }
67
72
 
73
+ /** @param {core.Record} row */
74
+ const payloadOf = (row) => /** @type {Record<string, any>} */ (JSON.parse(row.getString("payload") || "null") || {});
75
+
76
+ /**
77
+ * Change queue row `id` as it is stored now: what this pass loaded may be older (its claim, a fetch's edited
78
+ * messages, a send's steps). False when it is gone.
79
+ * @param {core.App} app
80
+ * @param {string} id
81
+ * @param {(row: core.Record) => void} change
82
+ */
83
+ function update(app, id, change) {
84
+ let found = false;
85
+ app.runInTransaction((tx) => {
86
+ let row;
87
+ try {
88
+ row = tx.findRecordById("tg_queue", id);
89
+ } catch {
90
+ return;
91
+ }
92
+ change(row);
93
+ tx.save(row);
94
+ found = true;
95
+ });
96
+ return found;
97
+ }
98
+
68
99
  /**
69
100
  * Send what is queued for Telegram, oldest first. A group whose oldest item has to wait (a failure that may pass, or
70
101
  * another pass sending it) gets nothing more this pass, so its messages arrive in order. `renew` after each one.
@@ -78,40 +109,53 @@ function drain(app, renew) {
78
109
  for (const row of rows) {
79
110
  if (!row) continue;
80
111
  const chat = row.getString("chat_id");
81
- if (blocked.has(chat)) continue;
112
+ const op = row.getString("op");
113
+ // What comes from a group (a fetch) waits apart from what goes to it: each keeps its own order.
114
+ const lane = op === "fetch" ? `in ${chat}` : chat;
115
+ if (blocked.has(lane)) continue;
82
116
  const due = row.getDateTime("next_at");
83
117
  if (!due.isZero() && due.time().unixMilli() > now) {
84
- blocked.add(chat);
118
+ blocked.add(lane);
85
119
  continue;
86
120
  }
87
121
  if (!claim(app, row.id)) {
88
- blocked.add(chat);
122
+ blocked.add(lane);
89
123
  continue;
90
124
  }
91
- const op = row.getString("op");
92
125
  const message = row.getString("message");
126
+ const tries = row.getInt("tries") + 1;
127
+ /** @type {Record<string, any>} */
128
+ let payload = payloadOf(row);
93
129
  try {
94
- if (op === "send") send(app, message, chat);
95
- else if (op === "edit") edit(app, message, chat);
130
+ if (op === "send") {
131
+ send(app, message, chat, payload.done || 0, (/** @type {number} */ done) => {
132
+ payload = { ...payload, done };
133
+ update(app, row.id, (r) => r.set("payload", payload));
134
+ });
135
+ } else if (op === "edit") edit(app, message, chat);
96
136
  else if (op === "delete") remove(app, message, chat);
97
137
  else if (op === "react") require(`${__hooks}/telegram/reactions.js`).react(app, message, chat);
138
+ else if (op === "fetch") fetchOver(app, row, tries >= MAX_TRIES);
98
139
  app.delete(row);
99
140
  } catch (err) {
100
- const tries = row.getInt("tries") + 1;
101
141
  const tg = asTelegram(err);
102
142
  const transient = !tg || tg.transient;
143
+ const unsure = (payload.unsure || 0) + (op === "send" && tg?.maybeDone ? 1 : 0);
103
144
  app.logger().warn(`telegram: ${op}`, "message", message, "chat", chat, "try", tries, "error", String(err));
104
- if (!transient || tries >= MAX_TRIES) {
145
+ if (!transient || tries >= MAX_TRIES || unsure > MAX_UNSURE) {
146
+ if (unsure > MAX_UNSURE) app.logger().warn(`telegram: ${op} dropped, it may have been sent`, "message", message, "chat", chat);
105
147
  app.delete(row);
106
148
  continue;
107
149
  }
108
150
  const wait = Math.max(tg ? tg.retryAfter : 0, 2 ** tries) * 1000;
109
- row.set("tries", tries);
110
- row.set("next_at", new DateTime(new Date(Date.now() + wait).toISOString()));
111
- row.set("locked_until", "");
112
- row.set("error", String(err).slice(0, 1000));
113
- app.save(row);
114
- blocked.add(chat);
151
+ update(app, row.id, (r) => {
152
+ r.set("tries", tries);
153
+ r.set("next_at", new DateTime(new Date(Date.now() + wait).toISOString()));
154
+ r.set("locked_until", "");
155
+ r.set("error", String(err).slice(0, 1000));
156
+ if (unsure) r.set("payload", { ...payloadOf(r), unsure });
157
+ });
158
+ blocked.add(lane);
115
159
  } finally {
116
160
  renew();
117
161
  }
@@ -0,0 +1,19 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Deleted accounts (DESIGN.md §43): `users.kind` gets "deleted", what an account is once its person deleted it
3
+ // (POST /api/chat/account/delete, pb_hooks/lib/account.js). The row stays, as "Deleted account", so that the messages
4
+ // and rooms naming it still have an author; nobody can sign in to it.
5
+
6
+ migrate(
7
+ (app) => {
8
+ const users = app.findCollectionByNameOrId("users");
9
+ const kind = /** @type {SelectField} */ (users.fields.getByName("kind"));
10
+ kind.values = ["person", "telegram", "peer", "deleted"];
11
+ app.save(users);
12
+ },
13
+ (app) => {
14
+ const users = app.findCollectionByNameOrId("users");
15
+ const kind = /** @type {SelectField} */ (users.fields.getByName("kind"));
16
+ kind.values = ["person", "telegram", "peer"];
17
+ app.save(users);
18
+ },
19
+ );
@@ -0,0 +1,45 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Account jobs (DESIGN.md §43.5): the work of "Your data" and "Delete account" that can be long on a big server, done
3
+ // by a worker (pb_hooks/lib/account.js) instead of in the request.
4
+ // - kind "export": a person's data, written a page at a time into `file` (a protected file, served only to them by
5
+ // GET /api/chat/export/file); kept 7 days.
6
+ // - kind "erase": a deleted account's collections, deleted a batch of items at a time, then with `messages` its
7
+ // messages, soft-deleted a batch at a time.
8
+ // No API rules: only the hooks read and write it.
9
+
10
+ const JOBS_ACCESS = { listRule: null, viewRule: null, createRule: null, updateRule: null, deleteRule: null };
11
+
12
+ migrate(
13
+ (app) => {
14
+ const users = app.findCollectionByNameOrId("users");
15
+ app.save(
16
+ new Collection(
17
+ /** @type {any} */ ({
18
+ type: "base",
19
+ name: "account_jobs",
20
+ ...JOBS_ACCESS,
21
+ fields: [
22
+ { type: "relation", name: "user", collectionId: users.id, cascadeDelete: true, maxSelect: 1, required: true },
23
+ { type: "select", name: "kind", values: ["export", "erase"], maxSelect: 1, required: true },
24
+ { type: "select", name: "state", values: ["queued", "done", "failed"], maxSelect: 1, required: true },
25
+ { type: "file", name: "file", maxSelect: 1, maxSize: 4 * 1024 * 1024 * 1024, protected: true },
26
+ { type: "number", name: "size", onlyInt: true, min: 0 },
27
+ { type: "bool", name: "messages" },
28
+ { type: "number", name: "tries", onlyInt: true, min: 0 },
29
+ { type: "text", name: "error", max: 500 },
30
+ { type: "date", name: "finished" },
31
+ { type: "autodate", name: "created", onCreate: true },
32
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
33
+ ],
34
+ indexes: [
35
+ "CREATE INDEX idx_account_jobs_state ON account_jobs (state, updated)",
36
+ "CREATE INDEX idx_account_jobs_user ON account_jobs (user, kind, created)",
37
+ ],
38
+ }),
39
+ ),
40
+ );
41
+ },
42
+ (app) => {
43
+ app.delete(app.findCollectionByNameOrId("account_jobs"));
44
+ },
45
+ );