summaryrefslogtreecommitdiffstats
path: root/netwerk/protocol/http/PendingTransactionQueue.cpp
blob: 9598769cc82d436b8f94b3f4d27298e86abb7fc5 (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
/* vim:set ts=4 sw=2 sts=2 et cin: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// HttpLog.h should generally be included first
#include "HttpLog.h"

// Log on level :5, instead of default :4.
#undef LOG
#define LOG(args) LOG5(args)
#undef LOG_ENABLED
#define LOG_ENABLED() LOG5_ENABLED()

#include "PendingTransactionQueue.h"
#include "nsHttpHandler.h"
#include "mozilla/ChaosMode.h"

namespace mozilla {
namespace net {

static uint64_t TabIdForQueuing(nsAHttpTransaction* transaction) {
  return gHttpHandler->ActiveTabPriority() ? transaction->BrowserId() : 0;
}

// This function decides the transaction's order in the pending queue.
// Given two transactions t1 and t2, returning true means that t2 is
// more important than t1 and thus should be dispatched first.
static bool TransactionComparator(nsHttpTransaction* t1,
                                  nsHttpTransaction* t2) {
  bool t1Blocking =
      t1->Caps() & (NS_HTTP_LOAD_AS_BLOCKING | NS_HTTP_LOAD_UNBLOCKED);
  bool t2Blocking =
      t2->Caps() & (NS_HTTP_LOAD_AS_BLOCKING | NS_HTTP_LOAD_UNBLOCKED);

  if (t1Blocking > t2Blocking) {
    return false;
  }

  if (t2Blocking > t1Blocking) {
    return true;
  }

  return t1->Priority() >= t2->Priority();
}

void PendingTransactionQueue::InsertTransactionNormal(
    PendingTransactionInfo* info,
    bool aInsertAsFirstForTheSamePriority /*= false*/) {
  LOG(
      ("PendingTransactionQueue::InsertTransactionNormal"
       " trans=%p, bid=%" PRIu64 "\n",
       info->Transaction(), info->Transaction()->BrowserId()));

  uint64_t windowId = TabIdForQueuing(info->Transaction());
  nsTArray<RefPtr<PendingTransactionInfo>>* const infoArray =
      mPendingTransactionTable.GetOrInsertNew(windowId);

  // XXX At least if a new array was empty before, this isn't efficient, as it
  // does an insert-sort. It would be better to just append all elements and
  // then sort.
  InsertTransactionSorted(*infoArray, info, aInsertAsFirstForTheSamePriority);
}

void PendingTransactionQueue::InsertTransactionSorted(
    nsTArray<RefPtr<PendingTransactionInfo>>& pendingQ,
    PendingTransactionInfo* pendingTransInfo,
    bool aInsertAsFirstForTheSamePriority /*= false*/) {
  // insert the transaction into the front of the queue based on following
  // rules:
  // 1. The transaction has NS_HTTP_LOAD_AS_BLOCKING or NS_HTTP_LOAD_UNBLOCKED.
  // 2. The transaction's priority is higher.
  //
  // search in reverse order under the assumption that many of the
  // existing transactions will have the same priority (usually 0).

  nsHttpTransaction* trans = pendingTransInfo->Transaction();

  for (int32_t i = pendingQ.Length() - 1; i >= 0; --i) {
    nsHttpTransaction* t = pendingQ[i]->Transaction();
    if (TransactionComparator(trans, t)) {
      if (ChaosMode::isActive(ChaosFeature::NetworkScheduling) ||
          aInsertAsFirstForTheSamePriority) {
        int32_t samePriorityCount;
        for (samePriorityCount = 0; i - samePriorityCount >= 0;
             ++samePriorityCount) {
          if (pendingQ[i - samePriorityCount]->Transaction()->Priority() !=
              trans->Priority()) {
            break;
          }
        }
        if (aInsertAsFirstForTheSamePriority) {
          i -= samePriorityCount;
        } else {
          // skip over 0...all of the elements with the same priority.
          i -= ChaosMode::randomUint32LessThan(samePriorityCount + 1);
        }
      }
      pendingQ.InsertElementAt(i + 1, pendingTransInfo);
      return;
    }
  }
  pendingQ.InsertElementAt(0, pendingTransInfo);
}

void PendingTransactionQueue::InsertTransaction(
    PendingTransactionInfo* pendingTransInfo,
    bool aInsertAsFirstForTheSamePriority /* = false */) {
  if (pendingTransInfo->Transaction()->Caps() & NS_HTTP_URGENT_START) {
    LOG(
        ("  adding transaction to pending queue "
         "[trans=%p urgent-start-count=%zu]\n",
         pendingTransInfo->Transaction(), mUrgentStartQ.Length() + 1));
    // put this transaction on the urgent-start queue...
    InsertTransactionSorted(mUrgentStartQ, pendingTransInfo);
  } else {
    LOG(
        ("  adding transaction to pending queue "
         "[trans=%p pending-count=%zu]\n",
         pendingTransInfo->Transaction(), PendingQueueLength() + 1));
    // put this transaction on the pending queue...
    InsertTransactionNormal(pendingTransInfo);
  }
}

nsTArray<RefPtr<PendingTransactionInfo>>*
PendingTransactionQueue::GetTransactionPendingQHelper(
    nsAHttpTransaction* trans) {
  nsTArray<RefPtr<PendingTransactionInfo>>* pendingQ = nullptr;
  int32_t caps = trans->Caps();
  if (caps & NS_HTTP_URGENT_START) {
    pendingQ = &(mUrgentStartQ);
  } else {
    pendingQ = mPendingTransactionTable.Get(TabIdForQueuing(trans));
  }
  return pendingQ;
}

void PendingTransactionQueue::AppendPendingUrgentStartQ(
    nsTArray<RefPtr<PendingTransactionInfo>>& result) {
  result.InsertElementsAt(0, mUrgentStartQ.Elements(), mUrgentStartQ.Length());
  mUrgentStartQ.Clear();
}

void PendingTransactionQueue::AppendPendingQForFocusedWindow(
    uint64_t windowId, nsTArray<RefPtr<PendingTransactionInfo>>& result,
    uint32_t maxCount) {
  nsTArray<RefPtr<PendingTransactionInfo>>* infoArray = nullptr;
  if (!mPendingTransactionTable.Get(windowId, &infoArray)) {
    result.Clear();
    return;
  }

  uint32_t countToAppend = maxCount;
  countToAppend = countToAppend > infoArray->Length() || countToAppend == 0
                      ? infoArray->Length()
                      : countToAppend;

  result.InsertElementsAt(result.Length(), infoArray->Elements(),
                          countToAppend);
  infoArray->RemoveElementsAt(0, countToAppend);

  LOG(
      ("PendingTransactionQueue::AppendPendingQForFocusedWindow, "
       "pendingQ count=%zu window.count=%zu for focused window (id=%" PRIu64
       ")\n",
       result.Length(), infoArray->Length(), windowId));
}

void PendingTransactionQueue::AppendPendingQForNonFocusedWindows(
    uint64_t windowId, nsTArray<RefPtr<PendingTransactionInfo>>& result,
    uint32_t maxCount) {
  // XXX Adjust the order of transactions in a smarter manner.
  uint32_t totalCount = 0;
  for (const auto& entry : mPendingTransactionTable) {
    if (windowId && entry.GetKey() == windowId) {
      continue;
    }

    uint32_t count = 0;
    for (; count < entry.GetWeak()->Length(); ++count) {
      if (maxCount && totalCount == maxCount) {
        break;
      }

      // Because elements in |result| could come from multiple penndingQ,
      // call |InsertTransactionSorted| to make sure the order is correct.
      InsertTransactionSorted(result, entry.GetWeak()->ElementAt(count));
      ++totalCount;
    }
    entry.GetWeak()->RemoveElementsAt(0, count);

    if (maxCount && totalCount == maxCount) {
      if (entry.GetWeak()->Length()) {
        // There are still some pending transactions for background
        // tabs but we limit their dispatch.  This is considered as
        // an active tab optimization.
        nsHttp::NotifyActiveTabLoadOptimization();
      }
      break;
    }
  }
}

void PendingTransactionQueue::ReschedTransaction(nsHttpTransaction* aTrans) {
  nsTArray<RefPtr<PendingTransactionInfo>>* pendingQ =
      GetTransactionPendingQHelper(aTrans);

  int32_t index =
      pendingQ ? pendingQ->IndexOf(aTrans, 0, PendingComparator()) : -1;
  if (index >= 0) {
    RefPtr<PendingTransactionInfo> pendingTransInfo = (*pendingQ)[index];
    pendingQ->RemoveElementAt(index);
    InsertTransactionSorted(*pendingQ, pendingTransInfo);
  }
}

void PendingTransactionQueue::RemoveEmptyPendingQ() {
  for (auto it = mPendingTransactionTable.Iter(); !it.Done(); it.Next()) {
    if (it.UserData()->IsEmpty()) {
      it.Remove();
    }
  }
}

size_t PendingTransactionQueue::PendingQueueLength() const {
  size_t length = 0;
  for (const auto& data : mPendingTransactionTable.Values()) {
    length += data->Length();
  }

  return length;
}

size_t PendingTransactionQueue::PendingQueueLengthForWindow(
    uint64_t windowId) const {
  auto* pendingQ = mPendingTransactionTable.Get(windowId);
  return (pendingQ) ? pendingQ->Length() : 0;
}

size_t PendingTransactionQueue::UrgentStartQueueLength() {
  return mUrgentStartQ.Length();
}

void PendingTransactionQueue::PrintPendingQ() {
  LOG(("urgent queue ["));
  for (const auto& info : mUrgentStartQ) {
    LOG(("  %p", info->Transaction()));
  }
  for (const auto& entry : mPendingTransactionTable) {
    LOG(("] window id = %" PRIx64 " queue [", entry.GetKey()));
    for (const auto& info : *entry.GetWeak()) {
      LOG(("  %p", info->Transaction()));
    }
  }
  LOG(("]"));
}

void PendingTransactionQueue::Compact() {
  mUrgentStartQ.Compact();
  for (const auto& data : mPendingTransactionTable.Values()) {
    data->Compact();
  }
}

void PendingTransactionQueue::CancelAllTransactions(nsresult reason) {
  for (const auto& pendingTransInfo : mUrgentStartQ) {
    LOG(("PendingTransactionQueue::CancelAllTransactions %p\n",
         pendingTransInfo->Transaction()));
    pendingTransInfo->Transaction()->Close(reason);
  }
  mUrgentStartQ.Clear();

  for (const auto& data : mPendingTransactionTable.Values()) {
    for (const auto& pendingTransInfo : *data) {
      LOG(("PendingTransactionQueue::CancelAllTransactions %p\n",
           pendingTransInfo->Transaction()));
      pendingTransInfo->Transaction()->Close(reason);
    }
    data->Clear();
  }

  mPendingTransactionTable.Clear();
}

}  // namespace net
}  // namespace mozilla