Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ The build step (`npm run build`) also runs `npm run docs`, which regenerates the
2. Validates OS compatibility using version config from `src/versions.ts`
3. Optionally installs SQL Native Client (`src/install-native-client.ts`) and ODBC driver (`src/install-odbc.ts`)
4. Downloads or cache-hits the SQL Server installer (box+exe, standalone exe, or SSEI bootstrapper)
5. Optionally downloads cumulative updates (resolves Microsoft download-page JSON, falls back to legacy `<a href>` links if the metadata is missing or unusable, fetches the page up to three times, retrying network errors, timeouts and non-2xx responses after 5 and then 10 seconds, and if resolving or downloading the update fails, warns and installs without updates)
5. Optionally downloads cumulative updates (when the runner's proxy settings apply to the Microsoft download page, by `getProxyUrl()` from `@actions/http-client`, fetches the page with `@actions/http-client`, like the downloads; it then follows redirects itself and reads each body as a stream with a 30-second limit, because `readBody()` never settles when the connection closes early; otherwise fetches the page with Node's `fetch` and a 30-second timeout, because Microsoft keeps refusing `@actions/http-client` requests for these pages from GitHub runners with HTTP 403; tries the page up to three times, retrying every failure after 5 and then 10 seconds; resolves the download-page JSON and falls back to legacy `<a href>` links if the metadata is missing or unusable; and if resolving or downloading the update fails, warns and installs without updates)
6. Runs the installer via `@actions/exec` (exit code 3010, "succeeded but reboot required", is logged as a warning and treated as success; any other non-zero code fails the action)
7. Waits for the database to be ready with `waitForDatabase()` from `src/utils.ts` (up to 6 `sqlcmd` logins with exponential backoff); if the database is not ready, or `sqlcmd` can't run, the action warns, or fails if setup exited 3010

Expand All @@ -66,7 +66,7 @@ The build step (`npm run build`) also runs `npm run docs`, which regenerates the

## Conventions

- **Testing:** Uses the built-in [`node:test`](https://nodejs.org/api/test.html) runner with `--experimental-test-module-mocks` and `node:assert/strict`. No Mocha, Chai, Sinon, or c8. Each test file mirrors its source file (e.g., `test/install.ts` tests `src/install.ts`).
- **Testing:** Uses the built-in [`node:test`](https://nodejs.org/api/test.html) runner with `--experimental-test-module-mocks` and `node:assert/strict`. No Mocha, Chai, Sinon, or c8. Each test file mirrors its source file (e.g., `test/install.ts` tests `src/install.ts`). `test/update-page-proxy.ts` is the exception: it fetches update pages through a real loopback CONNECT proxy with the unmocked `@actions/http-client`, so keep it unmocked.
- **Mocking pattern:** Create `mock.fn()` stubs at the top of the test file, call `mock.module(specifier, { namedExports, defaultExport })` for each dependency you need to replace, then `await import('../src/sut.ts')` to load the system-under-test against those mocks. Reset call history and implementations in `beforeEach` using `fn.mock.resetCalls()` and `fn.mock.mockImplementation(...)`. Because a given `mock.module()` call cannot be replaced mid-run, the tests share one mock per module across all cases and vary behaviour via `mockImplementation`/`mockImplementationOnce(impl, onCall)` — note that `mockImplementationOnce` without `onCall` applies to the next call, so a second one queued before that call replaces the first. Pass an explicit index when queueing sequential once-implementations.
- **Coverage caveat:** `--experimental-test-coverage` under-reports coverage for files that are `mock.module()`-replaced in sibling tests (the aggregator treats the mock shadow as an uncovered run of the real file). Running a source file's own test file in isolation gives a more accurate figure for that file, but not every file reaches 100% that way. Treat the aggregated numbers as a lower bound while this feature is experimental.
- **Commit messages:** Follow [Conventional Commits](https://www.conventionalcommits.org/) enforced by commitlint. Semantic-release uses these to generate automated releases and changelogs, so correct commit types are critical.
Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,34 @@ reason and installs SQL Server without updates. Update URLs are configured for
SQL Server 2016 and later, including 2025 (and so the default, `'latest'`);
older versions skip updates.

#### Proxies

When the runner's proxy settings (`HTTPS_PROXY` and `NO_PROXY`) apply to the
download page, the action fetches the page through the proxy. It uses the same
HTTP client as its downloads, and it writes a message about the proxy to the
log. Otherwise, the action fetches the page directly with Node's built-in
`fetch`, because Microsoft has refused many more requests from that HTTP client
than from `fetch`. If the action can't fetch the page through the proxy, set
`NO_PROXY` on the setup-sqlserver step to fetch the page directly:

```yaml
- uses: tediousjs/setup-sqlserver@v4
with:
install-updates: true
env:
NO_PROXY: www.microsoft.com
```

Only the download pages are on `www.microsoft.com`, so this doesn't change how
the action downloads the installers and updates.

The `NO_PROXY` of the step replaces the runner's value for that step only. So
add any other hosts from the runner's list that the step needs. Set it on the
step, not on the job, so that the other steps keep the runner's value. Each
entry also matches its subdomains, so `microsoft.com` or `.microsoft.com` also
sends the installer and update downloads directly. A `*.` wildcard doesn't
work.

### Caching

Downloaded SQL Server installers, cumulative updates, and ODBC and Native
Expand Down
6 changes: 3 additions & 3 deletions lib/main/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/main/index.js.map

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"@actions/core": "^3.0.1",
"@actions/exec": "^3.0.0",
"@actions/glob": "^0.7.0",
"@actions/http-client": "^4.0.1",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0"
}
Expand Down
156 changes: 136 additions & 20 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { mkdtemp, readdir } from 'node:fs/promises';
import { basename, extname, dirname, join as joinPaths, win32 } from 'node:path';
import type { IncomingMessage } from 'node:http';
import { text } from 'node:stream/consumers';
import { setTimeout as delay } from 'node:timers/promises';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as glob from '@actions/glob';
import { HttpClient } from '@actions/http-client';
import { getProxyUrl } from '@actions/http-client/lib/proxy';
import * as io from '@actions/io';
import * as tc from '@actions/tool-cache';
import { generateFileHash } from './crypto.ts';
Expand Down Expand Up @@ -401,30 +405,142 @@ function describeCause(cause: unknown): string {
return [message, code].filter(Boolean).join(' / ');
}

async function fetchUpdatePage(url: string): Promise<string> {
const attempts = 3;
for (let attempt = 1; ; attempt++) {
let retryable = false;
try {
const res = await fetch(url, { signal: AbortSignal.timeout(30_000) });
if (!res.ok) {
retryable = true;
throw new Error(`HTTP ${res.status}`);
/**
* The time limit in milliseconds for a cumulative update page request. Without a proxy, it limits the whole request.
* Through a proxy, it limits the time that the request can be idle, and the time that each body can take. A proxy that
* never answers the CONNECT request isn't limited, the same as for the downloads.
*/
const UPDATE_PAGE_TIMEOUT = 30_000;

/**
* The number of redirects that a cumulative update page request follows through a proxy, the same as Node's fetch.
*/
const MAX_PAGE_REDIRECTS = 20;

/**
* Describe a failure and its cause, for a log message.
*
* @param {unknown} error
* @returns {string}
*/
function describeError(error: unknown): string {
const reason = error instanceof Error ? error.message : String(error);
const causeDetails = error instanceof Error ? describeCause(error.cause) : '';
return causeDetails ? `${reason} (${causeDetails})` : reason;
}

/**
* Read the body of a cumulative update page response. HttpClientResponse.readBody() never settles when the
* connection closes before the end of the body, so read the stream, which then fails. Also fail when the body takes
* longer than UPDATE_PAGE_TIMEOUT.
*
* @param {IncomingMessage} message
* @param {string} url
* @returns {Promise<string>}
*/
async function readPageBody(message: IncomingMessage, url: string): Promise<string> {
const timer = setTimeout(() => message.destroy(new Error(`Request timeout: ${url}`)), UPDATE_PAGE_TIMEOUT);
try {
return await text(message);
} finally {
clearTimeout(timer);
}
}

/**
* Fetch a cumulative update page with Node's fetch. Node's fetch doesn't use the proxy settings unless
* NODE_USE_ENV_PROXY or --use-env-proxy is set when Node starts.
*
* @param {string} url
* @returns {Promise<string>}
*/
async function fetchPageWithFetch(url: string): Promise<string> {
const res = await fetch(url, { signal: AbortSignal.timeout(UPDATE_PAGE_TIMEOUT) });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return await res.text();
}

/**
* Fetch a cumulative update page with @actions/http-client, which follows the proxy settings. The client must not
* follow redirects itself: it reads each redirect body with readBody(), which never settles when the connection
* closes early, and it can't follow a relative Location.
*
* @param {HttpClient} client
* @param {string} url
* @returns {Promise<string>}
*/
async function fetchPageWithHttpClient(client: HttpClient, url: string): Promise<string> {
let current = new URL(url);
for (let redirects = 0; ; redirects++) {
const res = await client.get(current.href);
const body = await readPageBody(res.message, current.href);
const status = res.message.statusCode ?? 0;
const location = res.message.headers.location;
if (status >= 300 && status < 400 && location) {
if (redirects === MAX_PAGE_REDIRECTS) {
throw new Error(`More than ${MAX_PAGE_REDIRECTS} redirects`);
}
return await res.text();
} catch (error) {
retryable ||= error instanceof TypeError || (error instanceof Error && error.name === 'TimeoutError');
let reason = error instanceof Error ? error.message : String(error);
const causeDetails = error instanceof Error ? describeCause(error.cause) : '';
if (causeDetails) {
reason += ` (${causeDetails})`;
const next = new URL(location, current);
if (current.protocol === 'https:' && next.protocol !== 'https:') {
throw new Error(`Redirect from HTTPS to ${next.protocol} isn't allowed`);
}
if (!retryable || attempt === attempts) {
throw new Error(`Unable to fetch cumulative update page ${url} after ${attempt} attempt(s): ${reason}`, { cause: error });
current = next;
continue;
}
if (status < 200 || status > 299) {
throw new Error(`HTTP ${status}`);
}
return body;
}
}

/**
* Fetch a Microsoft download page, to find its cumulative update. When a proxy applies to the page, use
* @actions/http-client, which the downloads also use. The page request then follows the same proxy settings
* (HTTPS_PROXY and NO_PROXY). Otherwise use Node's fetch. Microsoft has refused @actions/http-client requests for
* these pages from GitHub runners with HTTP 403, and accepted Node's fetch from the same runners.
*
* @param {string} url
* @returns {Promise<string>} The page
*/
async function fetchUpdatePage(url: string): Promise<string> {
const attempts = 3;
const pageUrl = new URL(url);
// http-client uses the proxy only when its URL has a host name
const found = getProxyUrl(pageUrl);
const proxy = found?.hostname ? found : undefined;
// name the proxy by its host, but not when the proxy URL has credentials: if they aren't encoded, parts of them can
// end up in the host
const proxyValue = pageUrl.protocol === 'https:'
? process.env.https_proxy || process.env.HTTPS_PROXY
: process.env.http_proxy || process.env.HTTP_PROXY;
const proxyName = proxy && !proxyValue?.includes('@') ? `the proxy ${proxy.host}` : 'the proxy';
const proxyHint = proxy
? `. The request went through ${proxyName}. To fetch the page directly, set NO_PROXY=${pageUrl.hostname} on the setup-sqlserver step`
: '';
if (proxy) {
core.info(`Fetching the cumulative update page through ${proxyName}`);
}
const client = proxy
? new HttpClient('setup-sqlserver', [], { socketTimeout: UPDATE_PAGE_TIMEOUT, allowRedirects: false })
: undefined;
try {
for (let attempt = 1; ; attempt++) {
try {
return client ? await fetchPageWithHttpClient(client, url) : await fetchPageWithFetch(url);
} catch (error) {
const reason = describeError(error);
if (attempt === attempts) {
throw new Error(`Unable to fetch cumulative update page ${url} after ${attempt} attempt(s): ${reason}${proxyHint}`, { cause: error });
}
core.info(`Cumulative update page fetch failed (${reason}); retrying (${attempt + 1}/${attempts})`);
await delay(5000 * attempt);
}
core.info(`Cumulative update page fetch failed (${reason}); retrying (${attempt + 1}/${attempts})`);
await delay(5000 * attempt);
}
} finally {
client?.dispose();
}
}

Expand Down
Loading
Loading