Repository: microsoft/terminal
File: src/cascadia/TerminalConnection/AzureConnection.cpp (C++)

Code before:
        auto uri{ fmt::format(L"{}terminals?cols={}&rows={}&version=2019-01-01&shell={}", _cloudShellUri, _initialCols, _initialRows, shellType) };

        WWH::HttpStringContent content{
            L"{}",
            WSS::UnicodeEncoding::Utf8,
            // LOAD-BEARING. the API returns "'content-type' should be 'application/json' or 'multipart/form-data'"
            L"application/json"
        };

        const auto terminalResponse = _SendRequestReturningJson(uri, content, WWH::HttpMethod::Post(), Windows::Foundation::Uri(_cloudShellUri));
        _terminalID = terminalResponse.GetNamedString(L"id");

        auto socketUri = terminalResponse.GetNamedString(L"socketUri");

        // we have to do some post-handling to get the proper socket endpoint
        // the logic here is based on the way the cloud shell team itself does it
        winrt::hstring finalSocketUri;
        std::wstring wCloudShellUri{ _cloudShellUri };

        if (wCloudShellUri.find(L"servicebus") == std::wstring::npos)
        {
            // wCloudShellUri does not contain the word "servicebus", we can just use it to make the final URI

            // remove the "https://" from the cloud shell URI
            std::wstring https{ L"https://" };
            wCloudShellUri.replace(wCloudShellUri.find(https), https.length(), L"");

            finalSocketUri = fmt::format(FMT_COMPILE(L"wss://{}terminals/{}"), wCloudShellUri, _terminalID);
        }
        else
        {
            // if wCloudShellUri contains the word "servicebus", that means the returned socketUri is of the form
            // wss://ccon-prod-westus-aci-03.servicebus.windows.net/cc-AAAA-AAAAAAAA//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
            // we need to change it to:
            // wss://ccon-prod-westus-aci-03.servicebus.windows.net/$hc/cc-AAAA-AAAAAAAA/terminals/aaaaaaaaaaaaaaaaaaaaaa

            // get the substring up until the ".net"
            const std::wstring_view wSocketUri{ socketUri };
            const auto dotNetPos = wSocketUri.find(L".net") + 4;
            const auto wSocketUriBody = wSocketUri.substr(0, dotNetPos);

            // get the portion between the ".net" and the "//" (this is the cc-AAAA-AAAAAAAA part)
            const auto lastDoubleSlashPos = wSocketUri.find_last_of(L"//");
            const auto wSocketUriMiddle = wSocketUri.substr(dotNetPos, lastDoubleSlashPos - (dotNetPos));

            // piece together the final uri, adding in the "$hc" and "terminals" where needed
            finalSocketUri = fmt::format(FMT_COMPILE(L"{}/$hc{}terminals/{}"), wSocketUriBody, wSocketUriMiddle, _terminalID);
        }

        // Return the uri
        return winrt::hstring(finalSocketUri);

Review comment (suggestion):
In C++ code, valid usage of `string` and `wstring` is actually pretty rare. In this instance it's the same thing: This allocates 18 bytes of heap, copies the string constant there to make it mutable, and then it throws it immediately away after using it as a search needle.

Personally, during coding I always rely heavily on the language documentation. In case of C++ I pretty much always got cppreference open. Here it would be: https://en.cppreference.com/w/cpp/string/basic_string
That shows, that we can use the `erase()` function instead of `replace()`.

This would be fine IMO:
```cpp
wCloudShellUri.replace(wCloudShellUri.find(L"https://"), 8);
```
because while 8 is a magic number it's correlation with the find() string length is pretty obvious. Alternatively I'd make the https prefix a `static constexpr std::wstring_view` and use its `.size()`.

But we don't need to copy the URI into `wCloudShellUri` at all anyways. We _know_ that the `https://` will only ever be at the start of the string, so we can just trim off the first 5 characters here. Something like this:
```cpp
const auto uriWithoutProtocol = std::wstring_view{ _cloudShellUri }.substr(5);
finalSocketUri = fmt::format(FMT_COMPILE(L"wss{}terminals/{}"), uriWithoutProtocol, _terminalID);
```
(This could be augmented with a preceding `starts_with(L"https")` check, to ensure it works in case they ever return a `wss` URL on this endpoint... I guess.)

Code after:
        auto uri{ fmt::format(L"{}terminals?cols={}&rows={}&version=2019-01-01&shell={}", _cloudShellUri, _initialCols, _initialRows, shellType) };

        WWH::HttpStringContent content{
            L"{}",
            WSS::UnicodeEncoding::Utf8,
            // LOAD-BEARING. the API returns "'content-type' should be 'application/json' or 'multipart/form-data'"
            L"application/json"
        };

        const auto terminalResponse = _SendRequestReturningJson(uri, content, WWH::HttpMethod::Post(), Windows::Foundation::Uri(_cloudShellUri));
        _terminalID = terminalResponse.GetNamedString(L"id");

        // we have to do some post-handling to get the proper socket endpoint
        // the logic here is based on the way the cloud shell team itself does it
        winrt::hstring finalSocketUri;
        const std::wstring_view wCloudShellUri{ _cloudShellUri };

        if (wCloudShellUri.find(L"servicebus") == std::wstring::npos)
        {
            // wCloudShellUri does not contain the word "servicebus", we can just use it to make the final URI

            // remove the "https" from the cloud shell URI
            const auto uriWithoutProtocol = wCloudShellUri.substr(5);

            finalSocketUri = fmt::format(FMT_COMPILE(L"wss{}terminals/{}"), uriWithoutProtocol, _terminalID);
        }
        else
        {
            // if wCloudShellUri contains the word "servicebus", that means the returned socketUri is of the form
            // wss://ccon-prod-westus-aci-03.servicebus.windows.net/cc-AAAA-AAAAAAAA//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
            // we need to change it to:
            // wss://ccon-prod-westus-aci-03.servicebus.windows.net/$hc/cc-AAAA-AAAAAAAA/terminals/aaaaaaaaaaaaaaaaaaaaaa

            const auto socketUri = terminalResponse.GetNamedString(L"socketUri");
            const std::wstring_view wSocketUri{ socketUri };

            // get the substring up until the ".net"
            const auto dotNetStart = wSocketUri.find(L".net");
            THROW_HR_IF(E_UNEXPECTED, dotNetStart == std::wstring::npos);
            const auto dotNetEnd = dotNetStart + 4;
            const auto wSocketUriBody = wSocketUri.substr(0, dotNetEnd);

            // get the portion between the ".net" and the "//" (this is the cc-AAAA-AAAAAAAA part)
            const auto lastDoubleSlashPos = wSocketUri.find_last_of(L"//");
            THROW_HR_IF(E_UNEXPECTED, lastDoubleSlashPos == std::wstring::npos);
            const auto wSocketUriMiddle = wSocketUri.substr(dotNetEnd, lastDoubleSlashPos - (dotNetEnd));

            // piece together the final uri, adding in the "$hc" and "terminals" where needed
            finalSocketUri = fmt::format(FMT_COMPILE(L"{}/$hc{}terminals/{}"), wSocketUriBody, wSocketUriMiddle, _terminalID);
        }