Skip to content

Commit 68b6a2a

Browse files
authored
improvement(gitlab): reduce large-group overhead and pace outbound requests (#10738)
1 parent 2db84dd commit 68b6a2a

24 files changed

Lines changed: 645 additions & 96 deletions

File tree

‎apps/docs/content/docs/platform/self-hosting/environment-variables.mdx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,16 @@ A malformed entry in either allowlist stops the app at startup with a message na
274274

275275
Most `/api` routes also pass through Next.js Proxy, which buffers only the first 10 MiB with the current app configuration. Raising these variables or an external proxy limit does not raise that buffer. See [Request size limits](/platform/self-hosting/networking#request-size-limits) for the layers to configure.
276276

277+
## Outbound request limits
278+
279+
`OUTBOUND_REQUEST_LIMITS` optionally paces guarded HTTP requests by canonical organization and HTTPS origin. Entries share a Redis budget across application processes, sources and credentials. Configure the same policy on every app and worker process; Redis is required and an unavailable admission store prevents requests to the configured destination.
280+
281+
For example: `OUTBOUND_REQUEST_LIMITS='[{"organizationId":"org_example","origin":"https://gitlab.example.com","requestsPerMinute":480}]'`.
282+
283+
The origin must have no path, trailing slash, query or credentials. Up to 100 unique organization/origin pairs are supported, with integer ceilings from 1 to 60,000 requests/minute. Requests are paced without a startup burst; waits remain bounded by the operation's cancellation and a one-minute admission timeout. Existing installations are unchanged when this variable is unset.
284+
285+
This is an operating budget, not a provider quota or a firewall rule. It covers requests through Sim's guarded HTTP transport, including GitLab Search, discovery and retries. External CI jobs, direct SDK transports and personal/platform operations are outside this organization budget. A request to a configured origin without an established ownership scope fails closed. Keep provider-specific endpoint limits and operation timeouts in mind when choosing a ceiling.
286+
277287
## Limits
278288

279289
With `BILLING_ENABLED` disabled, hosted-plan execution rates/timeouts and table/storage quotas are not enforced unless you set their free-tier variables. Independent protocol, body-size, concurrency, and security rate limits still apply. Billing-enabled deployments enforce their plan limits.

‎apps/docs/content/docs/search/gitlab.mdx‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ The exporter makes only these GitLab API requests:
109109
| --- | --- |
110110
| `GET /api/v4/groups/:id` | Resolve a group identity when using `--group`. |
111111
| `GET /api/v4/groups/:id/projects` | Page through group projects, excluding shared projects; include subgroups only when requested. |
112-
| `GET /api/v4/projects/:id` | Resolve the numeric ID and full project path. |
112+
| `GET /api/v4/projects/:id` | Resolve a single-project export. Group exports reuse identities from the group listing. |
113113
| `GET /api/v4/projects/:id/members/all` | Page through visible direct, inherited, and invited-group members, 100 at a time. |
114114
| `GET /api/v4/users/:id` | Read each eligible member's account state, email confirmation, and primary email. |
115115

@@ -130,9 +130,19 @@ This creates `gitlab-permissions/users.csv` and `gitlab-permissions/project-perm
130130

131131
The export includes active, unlocked human members with Reporter access or higher. It excludes Guests, Planners, bots, and memberships expiring today or earlier in UTC. It does not infer access from public/internal visibility, administrator or Auditor privileges, or custom permissions below Reporter. GitLab policies such as SSO or external authorization are not represented by these CSVs. Review the grants against your organization's access requirements before uploading them.
132132

133-
Requests run serially, paced at 60 per minute by default. Set `--requests-per-minute` to change this export-job ceiling; it does not configure live Search traffic. Each run reads each project's identity and membership pages, plus one profile request per distinct candidate reader. Group exports also read the group identity and project listing. The request ceiling applies across the entire export. API errors, hidden emails, identity conflicts, inconsistent pagination totals (when GitLab provides them), and oversized exports stop the job without publishing either file. Run exports after bulk membership updates finish; paginated API reads are not a point-in-time snapshot.
133+
Requests run serially, paced at 60 per minute by default. Set `--requests-per-minute` to change this export-job ceiling; it does not configure live Search traffic. Group exports reuse project identities from the listing, read each project's membership pages, and fetch each distinct candidate reader's profile once. A second group listing checks for added, removed, moved or renamed projects before publishing. Every attempt, including retries, uses the same request ceiling. Transient connection failures, `429`, and retryable server errors get up to three retries, honoring `Retry-After` up to five minutes. Permanent errors, hidden emails, identity conflicts, inconsistent pagination, and oversized exports stop the job without publishing either file. Run exports after bulk membership updates finish; paginated API reads are not a point-in-time snapshot.
134134

135-
Large exports can take hours. For example, 50,000 projects require at least 100,000 project and membership requests, before listing and profile requests: over 27 hours at the default ceiling. Set the CI job timeout and schedule accordingly, or use smaller groups. Agree any higher request rate with your GitLab administrator. CSV files are written incrementally and published only when the complete export succeeds.
135+
For 50,000 projects with one membership page each, budget approximately 51,000 requests plus one profile lookup per distinct candidate reader. That is at least 14 hours at 60 requests/minute, or seven hours at 120, before extra membership pages, latency and retries. Use a separate source and CI job per top-level group, stagger jobs off-peak, and agree higher rates with your GitLab administrator. Each job has its own ceiling; simultaneous jobs add together. CSV files are written incrementally and published only when the complete export succeeds. Upload complete snapshots; changed-only CSVs would remove omitted grants.
136+
137+
## Plan Search capacity
138+
139+
Repository count is not the request count for a search. In CSV group mode, Sim uses group-level search where GitLab supports it, then verifies the projects of readable results. For example, one group-search page with results from ten projects needs about 13 GitLab requests. Opening a code or wiki result adds about five calls; an issue with a short discussion adds about seven. Broader queries, more groups, pagination and project-search fallbacks increase these counts. These are planning examples, not measured latency or fixed per-question limits.
140+
141+
These live Search sources do not periodically crawl projects. A 50,000-project catalog needs approximately 500 listing calls per discovery, plus identity checks. Saving group settings and replacing CSVs trigger discovery; a staged import validates at both creation and completion. Discovery must finish within five minutes. At low request ceilings, split the scope into smaller groups rather than assuming the maximum project count fits that deadline.
142+
143+
Sim can configure an organization-wide outbound ceiling for a GitLab host, shared by its Search sources and application processes. The CI exporter runs in your infrastructure and has a separate ceiling. Agree both budgets and GitLab's endpoint-specific limits before rollout. Self-hosted operators can use [`OUTBOUND_REQUEST_LIMITS`](/platform/self-hosting/environment-variables#outbound-request-limits).
144+
145+
One Search call covers at most 20 connected accounts. Skipped accounts are reported explicitly; API and MCP callers can repeat the query with `nativeQueries[].accountId`, targeting up to nine accounts per follow-up. The Search UI does not automatically traverse all remaining accounts. The group search candidate window described above also remains in effect.
136146

137147
## Access checks
138148

‎apps/docs/public/static/examples/gitlab/export-permissions.py‎

Lines changed: 61 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import argparse
55
import csv
66
from datetime import date, datetime, timezone
7+
from email.utils import parsedate_to_datetime
8+
from http.client import HTTPException
79
import io
810
import json
911
import os
@@ -53,20 +55,49 @@ def __init__(self, base_url, token, requests_per_minute):
5355
self.opener = build_opener(NoRedirects(), HTTPSHandler(context=ssl.create_default_context()))
5456

5557
def get(self, path, query=None):
56-
delay = self.interval - (time.monotonic() - self.last_request)
57-
if delay > 0:
58-
time.sleep(delay)
5958
url = self.base + path + ("?" + urlencode(query) if query else "")
6059
request = Request(url, headers={"PRIVATE-TOKEN": self.token, "Accept": "application/json"})
61-
self.last_request = time.monotonic()
62-
try:
63-
with self.opener.open(request, timeout=30) as response:
64-
raw = response.read(8 * 1024 * 1024 + 1)
65-
headers = response.headers
66-
except HTTPError as error:
67-
raise ExportError(f"GitLab GET {path} failed (HTTP {error.code}); no export published.") from None
68-
except (URLError, TimeoutError, OSError):
69-
raise ExportError("GitLab connection failed. Check the host, HTTPS trust, and network access.") from None
60+
for attempt in range(4):
61+
delay = self.interval - (time.monotonic() - self.last_request)
62+
if delay > 0:
63+
time.sleep(delay)
64+
self.last_request = time.monotonic()
65+
retry_after = None
66+
try:
67+
with self.opener.open(request, timeout=30) as response:
68+
raw = response.read(8 * 1024 * 1024 + 1)
69+
headers = response.headers
70+
declared_length = headers.get("Content-Length")
71+
if declared_length is not None:
72+
if not re.fullmatch(r"[0-9]{1,10}", declared_length):
73+
raise ExportError("GitLab returned an invalid response length.")
74+
if int(declared_length) > 8 * 1024 * 1024:
75+
raise ExportError("GitLab response exceeds the 8 MiB limit.")
76+
if len(raw) < int(declared_length):
77+
raise HTTPException("GitLab response ended before its declared length.")
78+
break
79+
except HTTPError as error:
80+
status = error.code
81+
retry_after = error.headers.get("Retry-After")
82+
error.close()
83+
message = f"GitLab GET {path} failed (HTTP {status}); no export published."
84+
if status not in (429, 500, 502, 503, 504) or attempt == 3:
85+
raise ExportError(message) from None
86+
except (URLError, TimeoutError, OSError, HTTPException) as error:
87+
message = "GitLab connection failed. Check the host, HTTPS trust, and network access."
88+
if attempt == 3 or isinstance(getattr(error, "reason", error), ssl.SSLCertVerificationError):
89+
raise ExportError(message) from None
90+
delay = 2 ** attempt
91+
if retry_after:
92+
try:
93+
seconds = (int(retry_after) if retry_after.isdigit() else
94+
parsedate_to_datetime(retry_after).timestamp() - time.time())
95+
delay = max(delay, seconds)
96+
except (ValueError, TypeError, OverflowError):
97+
pass
98+
if delay > 300:
99+
raise ExportError(message + " Retry after the provider's cooldown.")
100+
time.sleep(delay)
70101
if len(raw) > 8 * 1024 * 1024:
71102
raise ExportError("GitLab response exceeds the 8 MiB limit.")
72103
try:
@@ -119,8 +150,7 @@ def verified_email(profile, user_id):
119150
return email
120151

121152

122-
def export(client, project, profiles):
123-
record, _ = client.get("projects/" + resource_id(project))
153+
def project_identity(record):
124154
if not isinstance(record, dict):
125155
raise ExportError("GitLab returned an invalid project.")
126156
project_id = identifier(record.get("id"))
@@ -131,6 +161,15 @@ def export(client, project, profiles):
131161
or not all(char.isalnum() or char in "_.-" for char in part)
132162
for part in project_path.split("/"))):
133163
raise ExportError("GitLab returned an invalid project path.")
164+
return project_id, project_path
165+
166+
167+
def export(client, project, profiles, project_path=None):
168+
if project_path is None:
169+
record, _ = client.get("projects/" + resource_id(project))
170+
project_id, project_path = project_identity(record)
171+
else:
172+
project_id = identifier(project)
134173
users, emails, seen_members = {}, {}, set()
135174
today = datetime.now(timezone.utc).date()
136175
page = 1
@@ -222,13 +261,8 @@ def group_projects(client, group, include_subgroups):
222261
raise ExportError("GitLab group project total changed during export.")
223262
expected_total = int(total)
224263
for row in rows:
225-
if not isinstance(row, dict):
226-
raise ExportError("GitLab returned an invalid group project.")
227-
project_id = identifier(row.get("id"))
228-
project_path = row.get("path_with_namespace")
229-
if not isinstance(project_path, str) or len(project_path) > 1024:
230-
raise ExportError("GitLab returned an invalid project path.")
231-
namespace = project_path.rpartition("/")[0] if isinstance(project_path, str) else ""
264+
project_id, project_path = project_identity(row)
265+
namespace = project_path.rpartition("/")[0]
232266
if not (namespace == path or (include_subgroups and namespace.startswith(path + "/"))):
233267
raise ExportError("GitLab returned a project outside the configured group.")
234268
if project_id in seen_ids or project_path in seen_paths:
@@ -255,7 +289,7 @@ def group_projects(client, group, include_subgroups):
255289
raise ExportError("GitLab group project total does not match the complete listing.")
256290
if not projects:
257291
raise ExportError("No accessible projects in the GitLab group.")
258-
return sorted(projects)
292+
return group_id, path, sorted(projects)
259293

260294

261295
def write_export(output, grants, users):
@@ -315,21 +349,22 @@ def main():
315349
if output.exists() or output.is_symlink():
316350
raise ExportError("Output directory already exists. Choose a new directory for a fresh export.")
317351
client = GitLab(args.gitlab_url, token, args.requests_per_minute)
318-
projects = group_projects(client, args.group, args.include_subgroups) if args.group else [(args.project, None)]
352+
group_snapshot = group_projects(client, args.group, args.include_subgroups) if args.group else None
353+
projects = group_snapshot[2] if group_snapshot else [(args.project, None)]
319354
profiles, users, emails = {}, {}, {}
320355

321356
def grants():
322357
for project_id, expected_path in projects:
323-
project_path, readers = export(client, str(project_id), profiles)
324-
if expected_path is not None and expected_path != project_path:
325-
raise ExportError("GitLab project identity changed during export. Rerun the export.")
358+
project_path, readers = export(client, project_id, profiles, expected_path)
326359
for user_id in sorted(readers):
327360
email = readers[user_id]
328361
if email in emails and emails[email] != user_id:
329362
raise ExportError("Multiple GitLab users share an email. Resolve the identity conflict first.")
330363
emails[email] = user_id
331364
users[user_id] = email
332365
yield project_path, user_id
366+
if group_snapshot and group_snapshot != group_projects(client, args.group, args.include_subgroups):
367+
raise ExportError("GitLab group projects changed during export. Rerun the export.")
333368

334369
write_export(output, grants(), users)
335370
print(f"Exported {len(users)} readers to {output}/users.csv and {output}/project-permissions.csv")

‎apps/docs/public/static/examples/gitlab/upload-permissions.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def request(self, method, suffix, payload, retry=False):
147147
})
148148
delay = min(2 ** attempt, 30)
149149
try:
150-
with self.opener.open(request, timeout=120) as response:
150+
with self.opener.open(request, timeout=360) as response:
151151
raw = response.read(65537)
152152
if len(raw) > 65536:
153153
raise UploadError("Sim returned an oversized response.")

0 commit comments

Comments
 (0)