summaryrefslogtreecommitdiff
path: root/ui/lib/outbox.svelte.js
blob: fd7fdba1c861424cbe378f5ebcffaba52fda307e (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
import * as api from './apiServer.js';
import * as md from './markdown.js';

class PostToChannel {
  constructor(channel, body) {
    this.channel = channel;
    this.body = body;
    this.renderedBody = md.render(body);
  }

  async send() {
    return await api.retry(() => api.postToChannel(this.channel, this.body));
  }
}

class DeleteMessage {
  constructor(messageId) {
    this.messageId = messageId;
  }

  async send() {
    return await api.retry(() => api.deleteMessage(this.messageId));
  }
}

class CreateChannel {
  constructor(name) {
    this.name = name;
  }

  async send() {
    return await api.retry(() => api.createChannel(this.name));
  }
}

export class Outbox {
  pending = $state([]);

  static empty() {
    return new Outbox([]);
  }

  constructor(pending) {
    this.pending = pending;
  }

  enqueue(operation) {
    this.pending.push(operation);
    this.start();
  }

  createChannel(name) {
    this.enqueue(new CreateChannel(name));
  }

  postToChannel(channel, body) {
    this.enqueue(new PostToChannel(channel, body));
  }

  deleteMessage(messageId) {
    this.enqueue(new DeleteMessage(messageId));
  }

  start() {
    if (this.sending) {
      return;
    }
    // This is a promise transform primarily to keep the management of `this.sending` in one place,
    // rather than spreading it across multiple methods.
    this.sending = this.drain().finally(() => {
      this.sending = null;

      // If we encounter an exception processing the pending queue, it may have an operation left
      // in it. If so, start over. The exception will still propagate out (though since nothing
      // ever awaits the promise from this.sending, it'll ultimately leak out to the browser
      // anyways).
      if (this.pending.length > 0) {
        this.start();
      }
    });
  }

  async drain() {
    while (this.pending.length > 0) {
      const operation = this.pending[0];

      try {
        await operation.send();
      } finally {
        this.pending.shift();
      }
    }
  }
}