Commit Graph

8549 Commits

Author SHA1 Message Date
Jason Hawk Harris
cff1669bc1
Svelte: Perforce UI elements refactor (#64279)
## UI Updates for Perforce Depots and Git Repos

Fixes SRCH-530

**NOTE: This PR is a refactor of an earlier
[PR](https://github.com/sourcegraph/sourcegraph/pull/64014) that was
reverted. For that reason, the PR description is largely the same.**

This PR introduces changes to the UI to differentiate between Perforce
Depots and Git repositories. Below are the key changes included in this
commit:

### 1. Dynamic Top-Level Navigation

**For Perforce Depots:**

![Screenshot 2024-07-31 at 10 10 37
AM](https://github.com/user-attachments/assets/2d261b51-f8fa-4599-acae-3520d38996f3)

**For Git Repos:**

![Screenshot 2024-07-31 at 10 10 14
AM](https://github.com/user-attachments/assets/0f9ee3f7-918a-42d8-908f-04593ed52ebd)

### 2. Tabs on Revision Picker

**For Perforce Depots:**

Since we only need one tab for changelists, no tabs are shown.

![Screenshot 2024-07-31 at 10 20 24
AM](https://github.com/user-attachments/assets/f1006d56-67aa-41ab-a13b-905e157cb283)

**For Git Repos:**

We have tabs for Branches, Tags, and Commits.

![Screenshot 2024-07-31 at 10 23 02
AM](https://github.com/user-attachments/assets/38907d51-0407-4cd7-ad4c-1c5967dfddf3)

### 3. Commits/Changelists Page

**For Git Repos:**

The page displays Git commits.

![Screenshot 2024-07-31 at 10 26 23
AM](https://github.com/user-attachments/assets/85245d1d-708f-4d51-9da3-0425c3f085d0)

**For Perforce Depots:**

The page displays Perforce changelists.

![Screenshot 2024-07-31 at 10 26 39
AM](https://github.com/user-attachments/assets/2f6f16aa-d498-4763-949d-d1a13f9a26ac)

### 4. Vocabulary Adjustments

- We display either Git commit SHAs or Changelist IDs based on the
project type.
- For authorship, we use "submitted by" for Perforce and "committed by"
for Git.
- We refer to "Commits" for Git projects and "Changelists" for Perforce
projects.

**Examples:**

- **For Git Commits:**

![Screenshot 2024-07-31 at 10 37 08
AM](https://github.com/user-attachments/assets/ac15b0b3-4c85-4a4c-80c0-ec9384b72eca)

- **For Perforce Changelists:**

![Screenshot 2024-07-31 at 10 37 35
AM](https://github.com/user-attachments/assets/4230cb32-5285-4141-b374-f3ea23042e1d)

### 5. URL Mapping

URLs are now structured differently based on the project type:

- **Commits Page:**
  - Git: `/[repo-name]/-/commits`
  - Perforce: `/[repo-name]/-/changelists`
  
- **Individual Item Page:**
  - Git: `/[repo-name]/-/commit/[commit-hash]`
  - Perforce: `/[depot-name]/-/changelist/[changelist-ID]`

When viewing a specific commit or changelist:
- **Git:** `/[repo-name]@[git-commit-hash]`
- **Perforce:** `/[repo-name]@changelist/[changelist-id]`

_NOTE: The value displayed in the search field will also change
accordingly._


### What is left to be done?
**On repo search results, when searching a revision, we still show the
git commit SHA instead of the changelist ID for perforce depots:**
![Screenshot 2024-07-31 at 10 59 12
AM](https://github.com/user-attachments/assets/38bc2a3e-be8b-4585-9fe0-776149a7f230)

I plan to make a follow-up issue for this and begin work on it
immediately. It's a little trickier than the other changes because in
the RepositoryMatch type, there is no value that can help us determine
whether a project is a depot or a repo. We need to find another way to
fetch that data.

### Request for reviewers: 
1. Please try to break these new features and tell me what you find. I
stumbled on a number of little gotchas while working on this, and I'm
sure I've missed some.

## Test plan
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
- Manual/Visual testing
- Adjust e2e and integration tests to obtain a passing CI
- Test directly visiting a URL versus getting there via click
- Add unit tests for new/updated helper functions

---------

Co-authored-by: Camden Cheek <camden@ccheek.com>
2024-08-14 19:18:24 +00:00
Robert Lin
6e828b0a14
feat/dotcom: use Enterprise Portal for all subscriptions UI (#64115)
Overview Loom:

1.
https://www.loom.com/share/988465de1c3a4caaa08fc6b22ffb74e5?sid=860f28cd-4dfb-4758-9bd9-d2f485ceb317
2. Announcement:
https://www.loom.com/share/8560388e0a4a404caf67d908820ed0d0?sid=6482815f-ac60-4251-95cc-307f527a60dd

tl;dr


![image](https://github.com/user-attachments/assets/542c5b64-5729-4a6a-91b2-e0373abb35fa)

![image](https://github.com/user-attachments/assets/9cc41a80-2ff1-4845-a290-823df242cd2e)

![image](https://github.com/user-attachments/assets/47c9a400-d091-416f-a85c-f1dcc93d880d)

TODO:

- [x] Fix the "edit instance type" input
- [x] ~Subscription view: reload on changing the Enterprise Portal
environment selector~ ->
https://linear.app/sourcegraph/issue/CORE-245/dotcom-subscriptions-ui-enterprise-portal-instance-selector-doesnt,
use a jank reload for now
- [x] CI

Closes
https://linear.app/sourcegraph/issue/CORE-100/enterprise-portal-migrate-away-from-dotcom-db-as-source-of-truth

## Test plan

Manual testing for UI via `sg start dotcom` ->
https://sourcegraph.test:3443/site-admin/dotcom/product/subscriptions

The PRs this PR is stacked on top of implement testing of the backend
capabilities
2024-08-14 15:32:22 +00:00
Ólafur Páll Geirsson
1b1229c867
feat/API: implement /models and /models/{modelId} using TypeSpec (#64421)
Fixes CODY-3085
Fixes CODY-3086

Previously, there was no way for OpenAI clients to list the available
models on Sourcegraph or query metadata about a given model ID ("model
ref" using our internal terminology). This PR fixes that problem AND
additionally adds infrastructure to auto-generate Go models from a
TypeSpec specification.

[TypeSpec](https://typespec.io/) is an IDL to document REST APIs,
created by Microsoft. Historically, the Go code in this repository has
been the single source of truth about what exact JSON structures are
expected in HTTP request/response pairs in our REST endpoints. This new
TypeSpec infrastructure allows us to document these shapes at a higher
abstraction level, which has several benefits including automatic
OpenAPI generation, which we can use to generate docs on
sourcegraph.com/docs or automatically generate client bindings in
TypeScript (among many other use-cases).

I am planning to write an RFC to propose we start using TypeSpec for new
REST endpoints going forward. If the RFC is not approved then we can
just delete the new `tools/typespec_codegen` directory and keep the
generated code in the repo. It won't be a big difference in the end
compared our current manual approach of writing Go structs for HTTP
APIs.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
See test cases. I additionally wrote a basic python script with the
official OpenAI client to test that it works with this endpoint. First,
I ran `sg start minimal`. Then I wrote this script
```py
import os
from openai import OpenAI
from dotenv import load_dotenv
import httpx

load_dotenv()

openai = OpenAI(
    # base_url="https://api.openai.com/v1",
    # api_key=os.getenv("OPENAI_API_KEY"),
    base_url="https://sourcegraph.test:3443/api/v1",
    api_key=os.getenv("SRC_ACCESS_TOKEN"),
    http_client=httpx.Client(verify=False)
)

def main():
    response = openai.models.list()
    for model in response.data:
        print(model.id)
if __name__ == "__main__":
    main()

```
Finally, I ran 
```
❯ python3 models.py
anthropic::unknown::claude-3-haiku-20240307
anthropic::unknown::claude-3-sonnet-20240229
fireworks::unknown::starcoder
```
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

* New `GET /.api/llm/models` and `GET /.api/llm/models/{modelId}` REST
API endpoints to list available LLM models on the instance and to get
information about a given model. This endpoints is compatible with the
`/models` and `/models/{modelId}` endpoints from OpenAI.

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-14 10:47:00 +00:00
Julie Tibshirani
c222523fa5
Redis: remove some direct pool usages (#64447)
We want to discourage direct usage of the Redis pool in favor of routing
all calls through the main `KeyValue` interface. This PR removes several
usages of `KeyValue.Pool`. To do so, it adds "PING" and "MGET" to the
`KeyValue` interface.
2024-08-14 13:39:10 +03:00
Petri-Johan Last
d3a3d721d3
Add support for Bitbucket Server OAuth2 (#64179)
Docs here: https://github.com/sourcegraph/docs/pull/561

This PR adds support for using Bitbucket Server OAuth2 application links
for sign-in and permission syncing.

When used for permission syncing, the user's oauth token is used to
fetch user permissions (and now permissions are fetched via the server).

## Test plan

Tests added and updated.

## Changelog

- Sourcegraph now supports Bitbucket Server OAuth2 application links for
user sign-in and permission syncing.
2024-08-14 12:24:32 +02:00
Craig Furman
bcb2e16d0b
feat(appliance): optionally load pinned releases file (#64441)
**chore(appliance): version list obtained from backend**

Instead of calling release registry directly from the frontend. This
commit is just preparation for a fallback mechanism for users that do
not want the external dependency on release registry.



**feat(appliance): optionally load pinned releases file**

Instead of calling release registry. This is a fallback mechanism for
airgap users.



**feat(appliance): respect pinned release versions during self-update**
2024-08-14 09:24:51 +01:00
Julie Tibshirani
ca6e72fe18
Redis: remove RedisKeyValue constructor (#64442)
This PR removes the `redispool.RedisKeyValue` constructor in favor of
the `New...KeyValue` methods, which do not take a pool directly. This
way callers won't create a `Pool` reference, allowing us to track all
direct pool usage through `KeyValue.Pool()`.

This also simplifies a few things:
* Tests now use `NewTestKeyValue` instead of dialing up localhost
directly
* We can remove duplicated Redis connection logic in Cody Gateway
2024-08-14 11:24:32 +03:00
Felix Kling
34ff925ed8
feat(svelte): Add cody chat page (#64448)
Closes #srch-906

This commit adds the cody chat page to svelte. This is simply reusing
the existing wrapper around the React component and renders it in a
standalone page.

When merged this will cause the cody chat page to be handled by new web
app on dotcom by default.

## Test plan

- Verified that chat loads and the tabs are clickable.
- Verified that the scroll behavior works as in the React app.
- Verified that the sidebar chat still works as expected (scroll
behavior, default context loading/switching)
2024-08-13 19:25:32 +00:00
Robert Lin
043e780590
feat/enterpriseportal: add license creation webhook (#64422)
Closes https://linear.app/sourcegraph/issue/CORE-241
Originally added in
https://github.com/sourcegraph/sourcegraph/pull/59214

This seems unused, but might be good to have for completedness-sake

## Test plan

Unit tests
2024-08-13 12:11:03 -07:00
Robert Lin
2649987bac
fix/enterpriseportal: [MUST REVERT LATER] relax scopes for write operations (#64453)
Staging this PR in case we don't find a way to unblock
https://sourcegraph.slack.com/archives/C079SAU0E72/p1723573784387739?thread_ts=1723566345.486509&cid=C079SAU0E72.
If this passes CI first, I'll roll this out to Enterprise Portal to
unblock TS/CE

This is needed because we can't roll out
https://github.com/sourcegraph/sourcegraph/pull/64450 due to a stuck
migration

## Test plan

n/a
2024-08-13 11:58:49 -07:00
Robert Lin
27d0615a3d
dotcom: request write scopes for EP prod proxy (#64450)
doh

## Test plan

n/a
2024-08-13 16:14:57 +00:00
Robert Lin
adce59be48
fix/enterpriseportal: adjust job check frequency, tweak messaging (#64418)
- The time.Second frequency is too frequent to be checking if the job
should be run, I think I set this in testing
- Adjust the Slack messaging to say `Active license`
- Adjust the Slack messaging to include the Salesforce subscription ID

## Test plan

Tests
2024-08-13 09:11:08 -07:00
Ólafur Páll Geirsson
7b1bc10a30
chore/API: speed up edit/test feedback loop for llmapi module (#64437)
Previously, it took ~6 seconds for a single edit/test/debug feedback
loop in the `llmapi` module. After this change, it's now 1-2s.

The reason the feedback loop was slow was that we depended on the
`//cmd/frontend/internal/modelconfig` target, which transitively brings
in `graphqlbackend` and all the migration code, which adds huge overhead
to Go link times. It was relatively easy to untangle this dependency so
I went ahead and removed it to boost my local feedback loop.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
Green CI.

To measure the timing, I ran the tests, made a tiny change and ran the
tests against to measure the total time to build+test.

```
# Before
❯ time go test -timeout 30s github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi
ok  	github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi	2.394s
go test -timeout 30s   4.26s user 4.73s system 166% cpu 5.393 total

# After
❯ time go test -timeout 30s github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi
ok  	github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi	0.862s
go test -timeout 30s   1.20s user 1.21s system 135% cpu 1.774 total
```
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 11:48:15 +00:00
Ólafur Páll Geirsson
47b66397da
feat/API: move from /api/v1 to /.api/llm (#64435)
Fixes CODY-3269

Previously, the OpenAI-compatible API endpoints had paths like
`/api/v1/chat/completions`, which went against an existing convention of
keeping all APIs under the `/.api` prefix. We have a fair amount of
internal tooling centered around the assumption that APIs have the
`/.api` prefix so this PR corrects the mistake and moves the
`/api/v1/chat/completions` endpoint to `/.api/llm/chat/completions`.

I went with the prefix `/.api/llm` since these allow clients to interact
with LLM features like `/chat/completions` or listing model information.
These APIs happen to be compatible with OpenAI APIs but I think it will
be more confusing to add something like "openai" or "openaicomptable" in
the API endpoint. We can just document on our website that these
endpoints are compatible with OpenAI clients.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Green CI. I also manually confirmed that I was able to use an OpenAI
client to send requests to the new APIs.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

* Moved `/api/v1/chat/completions` to `/.api/llm/chat/completions`. The
functionality is unchanged.

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 10:21:27 +00:00
Ólafur Páll Geirsson
70aa6908ea
fix/API: make requests to /api/console work again (#64429)
Fixes CODY-3267

Previously, requests to `/api/` matched the new `publicrestapi` module,
which meant that requests to the GraphQL `/api/console` no longer
worked. This PR fixes the problem by narrowing the prefix-match to
`/api/v1` so that it no longer matches `/api/console`.

I kept the scope of this PR narrow and only fixed the /api/console bug.
I will share a separate RFC to seek input on the tradeoffs between
/api/v1 and /.api. I can make that change separately if there's wide
consensus in #wg-architecture that we want to keep all API endpoints
(public and internal-facing) under /.api.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Ran `sg start minimal` and confirmed that I'm able to visit the URL
https://sourcegraph.test:3443/api/console

On the main branch, the same URL leads to a 404 page.

I also confirmed that the `/api/v1/chat/completions` endpoint still
works as expected.

```hurl
POST https://sourcegraph.test:3443/api/v1/chat/completions
Content-Type: application/json
Authorization: Bearer {{token}}
{
  "model": "anthropic::unknown::claude-3-sonnet-20240229",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Respond with \"no\" and nothing else"
        }
      ]
    }
  ],
  "temperature": 1,
  "max_tokens": 256,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0
}
```
```sh
❯ hurl hurl-scratchpad/openai-sg.hurl
{"id":"chat-1727acdf-6850-4387-950b-2e89850071fa","choices":[{"finish_reason":"end_turn","index":0,"message":{"content":"no","role":"assistant"}}],"created":1723536215,"model":"anthropic::unknown::claude-3-sonnet-20240229","system_fingerprint":"","object":"chat.completion","usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
```

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 10:04:40 +02:00
Robert Lin
cec288dc89
fix/enterpriseportal, fix/codygateway: zero-value durations and missing active licenses (#64378)
This change ensure we correctly handle:

1. In Enterprise Portal, where no active license is available, we return
ratelimit=0 intervalduration=0, from the source `PLAN` (as this is
determined by the lack of a plan)
2. In Cody Gateway, where intervalduration=0, we do not grant access to
that feature

## Test plan

Unit tests
2024-08-12 11:49:54 -07:00
Jean-Hadrien Chabran
991355ba02
chore(ci): shard authz test (#64413)
Similar to https://github.com/sourcegraph/sourcegraph/pull/64412 

## Test plan

CI
2024-08-12 14:50:01 +00:00
Julie Tibshirani
e65e736cb1
Redis: simplify DeleteAllKeysWithPrefix (#64407)
The `DeleteAllKeysWithPrefix` method is now only used in tests to ensure
the test keyspace is clear. This PR makes it clear this method is only
used in tests, and simplifies the implementation so it no longer needs a
script + direct Redis connection.

Another tiny Redis refactor to prepare for multi-tenancy work.
2024-08-12 15:25:33 +03:00
Julie Tibshirani
fae95fdf13
Search: boost phrases in hybrid search (#64367)
This PR passes the 'boost' annotation down to searcher, so that it can
apply phrase boosting. For now, we just pass the boost to the Zoekt
query in hybrid search, which already gives a nice benefit since the
Zoekt results are streamed back first.

Note: this doesn't completely implement boosting in searcher, but it was
really simple and seemed worth it. We're purposefully not investing in
big searcher ranking improvements, since we think a better investment is
to unify logic across Zoekt + searcher.
2024-08-12 11:24:51 +03:00
Robert Lin
02ac0214ee
chore/enterpriseportal: manual E2E test suite (#64057)
Adds a super simple E2E test suite that must be run with `sg test
enterprise-portal-e2e` against a locally running Enterprise Portal
instance. This is not intended to be filled with super granular
assertions - it simply tests that everything is wired up correctly and
runs end-to-end.

Caught at ~3 issues with this already, amended various downstack PRs
with the fix 😆

Closes
https://linear.app/sourcegraph/issue/CORE-229/enterprise-portal-basic-manual-e2e-testing-setup

## Test plan

```
sg start dotcom
sg test enterprise-portal-e2e
```

No additional configuration required, the defaults work as-is
2024-08-09 19:37:52 -07:00
Robert Lin
082535836a
feat/enterpriseportal: add instance category (#64253)
Per some feedback around
https://docs.google.com/document/d/1NyBIQvZ-ziNhiz7Yuzbp4f72Gp6EUrVUoBYnnnviXi8/edit,
this adds a "instance type" enumeration for each subscription:

1. PRIMARY: production
2. SECONDARY: dev/testing/staging/whatever
3. INTERNAL: for us

## Test plan

Updated tests
2024-08-09 18:19:51 -07:00
Robert Lin
e2c646ad92
feat/enterpriseportal: all subscriptions APIs use enterprise portal DB (#63959)
This change follows
https://github.com/sourcegraph/sourcegraph/pull/63858 by making the
_all_ subscriptions APIs read and write to the Enterprise Portal
database, instead of dotcomdb, using the data that we sync from dotcomdb
into Enterprise Portal.

With this PR, all initially proposed subscriptions APIs are at least
partially implemented.

Uses https://github.com/hexops/valast/pull/27 for custom `autogold`
rendering of `utctime.Time`

Closes https://linear.app/sourcegraph/issue/CORE-156
Part of https://linear.app/sourcegraph/issue/CORE-158

## Test plan

- [x] Unit tests on API level
- [x] Adapters unit testing
- [x] Simple E2E test:
https://github.com/sourcegraph/sourcegraph/pull/64057
2024-08-09 17:26:18 -07:00
Felix Kling
8296e9804f
feat(svelte): Migrate dotcom community search pages to Svelte (#64388)
What: This PR does the bare minimum to migrate the current community
search pages to Svelte. A better strategy for managing them is needed in
the medium/long term.

How: The community pages live at the root (e.g. `/kubernetes`) which
complicates things, but I'll get to that later. The page is implemented
as a single parameterized route. A parameter matcher is used to validate
the community name. Because these pages should only be accessible on
dotcom the matcher also validates whether or not we are on dotcom (if
not, the path will be matched against a different route).

The page config is stored in a separate module so that it's no included
in every page and so that it can be used in the integration test.

The loader and page implementation themselves are straightforward. I
made a couple of changes in other modules to make implementation easier:

- Extracted the parameter type of the `marked` function so that it can
be used as prop type.
- Added an `inline` option to `marked` that allows formatting markdown
as 'inline', i.e. without `p` wrapper.
- Added a `wrap` prop to `SyntaxHighlightedQuery.svelte` to configure
line wrapping of syntax highlighted search queries (instead of having to
overwrite styles with `:global`).
- Extended the route code generator to be able to handle single
parameter segments and the `communitySearchContext` matcher.

Because the community routes should only be available on dotcom I added
a new tag to the code generator that allows it include routes only for
dotcom.
Once we change how all this works and have community search pages live
under a different path we can simplify this again.

Result:

| React | Svelte |
|--------|--------|
|
![2024-08-09_16-05](https://github.com/user-attachments/assets/a64c4e0c-a9dd-4248-9466-05b348559408)
|
![2024-08-09_16-04](https://github.com/user-attachments/assets/d8ad424b-d04a-4590-b198-a6b2f4a76816)
|


## Test plan

- New integration tests.
- Verified that `/kubernetes` shows a 'repo not found error' when
running against S2.
- Verified that `/kubernetes` shows the community page when running
against dotcom.
- Verified that `window.context.svelteKit.enabledRoutes` contains the
community page route in enterprise mode but not in dotcom mode.
2024-08-09 22:52:47 +02:00
Robert Lin
0de249daf9
feat/enterpriseportal: more list options for subscriptions and licenses (#64114)
Required to build an updated subscriptions management UI.

Most of the diff is generated proto for some reason

Closes https://linear.app/sourcegraph/issue/CORE-226

## Test plan

Integration tests
2024-08-09 16:43:39 +00:00
Taras Yemets
14a4d7ce31
fix(cody): filter out deprecated models (#64381) 2024-08-09 16:37:42 +00:00
Robert Lin
8537000f9d
feat/enterpriseportal: existing subscriptions read APIs use enterprise portal DB (#63927)
This change follows
https://github.com/sourcegraph/sourcegraph/pull/63858 by making the
existing subscriptions APIs _read_ from the Enterprise Portal database,
instead of dotcomdb, using the data that we sync from dotcomdb into
Enterprise Portal.

Part of https://linear.app/sourcegraph/issue/CORE-156
Part of https://linear.app/sourcegraph/issue/CORE-158

## Test plan

Updated unit and integration tests
2024-08-09 09:36:40 -07:00
Robert Lin
3e9fe3a0b9
chore/enterpriseportal: make sf_opp_id license-level (#64087)
Per feedback on
https://docs.google.com/document/d/1NyBIQvZ-ziNhiz7Yuzbp4f72Gp6EUrVUoBYnnnviXi8/edit#heading=h.3lhmwnxotdew
and further research, the salesforce opportunity ID must be
license-level. Right now we keep this specific to the "license key"
license type.

## Test plan

CI
2024-08-09 16:16:37 +00:00
Robert Lin
43184a3dfe
feat/enterpriseportal: license expiry checker (#64317)
Port of the existing background job:
https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/internal/dotcom/productsubscription/license_expiration.go?L25:6-25:45,
originally added in
https://github.com/sourcegraph/sourcegraph/pull/10362

Most of the diff is generated mocks :)

Closes https://linear.app/sourcegraph/issue/CORE-183

## Test plan

- [x] Unit tests
- [x] Manual test:
```
[enterprise-...l] INFO service.licenseexpiration.store licenseexpiration/store.go:96 PostToSlack {"text": "The license for subscription `coreservices - Robert Lin - 2024-07-16 23:16:13` <https://sourcegraph.com/site-admin/dotcom/product/subscriptions/bee0a0d9-6c17-4acf-81a4-fd6e777ed6a4|will expire *in the next 24 hours*> 🚨"}
```
2024-08-09 09:08:59 -07:00
Anton Sviridov
db87eb601b
Use correct DSN for schema validation in syntactic worker (#64383)
Connecting to the wrong DSN leads to a cryptic error:

```
      Message:     {"SeverityText":"FATAL","Timestamp":1723196934012096886,"InstrumentationScope":"init db (syntactic-codeintel-worker)","Caller":"shared/shared.go:87","Function":"github.com/sourcegraph/sourcegraph/cmd/syntactic-code-intel-worker/shared.initCodeintelDB","Body":"Failed to connect to codeintel database","Resource":{"service.name":"syntactic-code-intel-worker","service.version":"286647_2024-08-08_5.6-34a7914fb884","service.instance.id":"syntactic-code-intel-worker-7bb9ccc75c-mkzpk"},"Attributes":{"error":"database schema out of date"}}
```

## Test plan
- existing tests should continue to pass


<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-09 11:21:33 +01:00
Ólafur Páll Geirsson
ba85ea6f32
feat/API: add publicly available /api/v1/chat/completions REST endpoint (#64239)
Fixes CODY-3081

This is the first PR for the project [⏭️ Launch Cody API
Experimental](https://linear.app/sourcegraph/project/launch-cody-api-experimental-8fd5ec338bf4),
which falls under the umbrella of moving Cody's brains to the cloud.

Previously, there was no publicly available REST API for our customers
to interact with Cody. This is a frequently requested feature from
customers and prospects.

This PR adds a new `POST /api/v1/chat/completions` endpoint, which
should be compatible with existing OpenAI clients. The OpenAI API format
is increasingly becoming an industry standard so this seems like a good
first step towards exposing a stable publicly facing API for our
customers.

The goal is to add more Cody-specific APIs in the coming weeks to send
chat messages and reference context.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

See added test cases.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

* API: new publicly available `/api/v1/chat/completions` REST endpoint
that is compatible with OpenAI clients with some restrictions. The detailed list of restrictions will eventually be documented on sourcegraph.com/docs

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-09 09:36:27 +00:00
Robert Lin
7c2d97858a
feat/dotcom: UI tracks Cody Gateway access directly in Enterprise Portal (#64090)
Upgrades the self-contained Cody Gateway modal to only depend on
Enterprise Portal to read/write Cody Gateway access.

I also made some minor tweaks to parsing empty form inputs, and also
made the "Cody Gateway access token" collapsed by default, with warnings
to discourage its use (opted not to remove entirely since it may be
useful for dev/debugging)

Depends on:

- https://github.com/sourcegraph/sourcegraph/pull/63926 
- https://github.com/sourcegraph/sourcegraph/pull/63925 
- https://github.com/sourcegraph/sourcegraph/pull/63858 

Closes https://linear.app/sourcegraph/issue/CORE-218

## Test plan

```
sg start dotcom
```

Edit the Cody Gateway access stuff, toggling it up and down.
Cross-reference with the `enterprise_portal_cody_gateway_access` table.
2024-08-08 16:37:16 -07:00
Robert Lin
447570628b
fix/enterpriseportal/codyaccess: allow removing rate limit overrides (#64376)
On double-checking the various Cody Gateway access management CRUD I
noticed that I did not implement the ability to remove the override
entirely properly - right now, removing a rate limit with `field_mask`
and no values results in a zero-value rate limit rather than a null one
as desired.

This change makes it so that if you provider a nil `*_rate_limit`
object, all field paths for that object is also set to nil, removing the
override and allowing the default active-license-plan-based rate limits
to apply.

This also adds a minor adjustment to Cody Gateway to correctly handle
zero durations for rate limit intervals, which should be treated as "no
access".

## Test plan

Unit/integration tests, and a manual test:

- Check out https://github.com/sourcegraph/sourcegraph/pull/64090 and
run `sg start dotcom`
- Go to a subscription, add a rate limit override 

![image](https://github.com/user-attachments/assets/9f417a60-5096-4f6e-8eea-1f0720cb4ada)
- Click the 🗑️ button to remove the rate limit override 

![image](https://github.com/user-attachments/assets/d53f4ae9-43d9-4bb2-a33b-7632f74ea2c8)
- Repeat above on each property
2024-08-08 15:19:58 -07:00
Robert Lin
076498f2dc
feat/enterpriseportal: implement UpdateCodyGatewayAccess (#63926)
Implements the only Cody Access write API we have right now, the ability
to apply overrides to Cody Gateway rate limits, which we'll have in
Enterprise Portal with
https://github.com/sourcegraph/sourcegraph/pull/63858

A lot of the diff is a new generated mock for the Cody Access store so
that we can write some simple unit tests.

With this addition, all initially proposed Cody Gateway access APIs are
implemented.

Part of https://linear.app/sourcegraph/issue/CORE-218
Closes https://linear.app/sourcegraph/issue/CORE-160

## Test plan

Unit and existing integration tests
2024-08-08 13:21:18 -07:00
Robert Lin
05ca108105
feat/enterpriseportal: use database for reading Cody Gateway access (#63925)
This change follows
https://github.com/sourcegraph/sourcegraph/pull/63858 by making the Cody
Access APIs _read_ from the Enterprise Portal database, instead of
dotcomdb, using the data that we sync from dotcomdb into Enterprise
Portal.

As part of this, I also expanded the existing "compatibility" test suite
that compares the result of our dotcomdb queries against the existing
GraphQL resolvers in dotcom to also compare the results of our new Cody
Access APIs, to validate that they return the same access.

> [!WARNING]
> There is one behavioural change, which is that hashes of _expired
licenses_ will no longer be valid as access tokens. This shouldn't be an
issue if customers use zero-config (implied access token from their
license key) - I will do some outreach before rolling this out.

Subsequent PRs will implement write APIs.


Part of https://linear.app/sourcegraph/issue/CORE-218
Part of https://linear.app/sourcegraph/issue/CORE-160

## Test plan

Integration and unit tests at various layers
2024-08-08 10:39:14 -07:00
Erik Seliger
55cdb4961c
graphqlbackend: Move utils to internal/ (#64117)
The utils are currently used outside of cmd/frontend, so to break the
internal -> cmd import I'm moving and merging the utils package with
internal/gqlutil.

Test plan: Just moved around and renamed a package, the go compiler
doesn't complain.
2024-08-08 14:18:37 +02:00
Erik Seliger
f61ce6e8e8
tenant: Introduce first version of tenant package (#64271)
This PR aims to craft the /internal/tenant package for use by all Sourcegraph cluster-internal services to properly scope data visibility to the correct requesting tenant.
For now, we only expose methods we know we will DEFINITELY need.

This PR also adds the required middlewares so we can start to tinker with it in implementations.

## Test plan

CI passes. We don't enforce anything for now except not passing unparseable tenant IDs, which should be fine.
2024-08-08 12:02:19 +02:00
Erik Seliger
a3f23a5972
searcher: Consolidate FetchTar and FetchTarPaths (#64268)
There was a todo comment that said we want to consolidate them but didn't yet to keep another diff smaller - so now we're doing that.

Test plan: Integration tests for search still pass.
2024-08-08 11:04:38 +02:00
Erik Seliger
5a39f81d84
chore: Move cmd/frontend/backend to internal (#64261)
To prevent cross-cmd imports in the future, moving the backend package into internal.

Test plan: Just moved a package around, Go compiler doesn't complain and CI still passes.
2024-08-08 11:02:51 +02:00
Noah S-C
b9c4e2aae9
Revert "Revert "refactor: upgrade to rules_oci 2.0 (2nd attempt)"" (#64354)
Reverts sourcegraph/sourcegraph#64351

## Test plan

Need to test on main due to main-only CI steps (even with main dry-run)
2024-08-08 09:00:08 +00:00
Erik Seliger
db550f9618
auth: Remove redirects to session package (#64260)
These functions are not required to be called outside of frontend, so there's no need to reexport them. Instead, we consolidate the signout cookie logic in the session package.

Test plan: Just moved some code around, go compiler doesn't complain.
2024-08-08 10:40:53 +02:00
Erik Seliger
8de09ddbc7
chore: Cleanup more cross-cmd imports (#64259)
This PR fixes a few more imports from /internal/ packages using /cmd/... contents.

Test plan: Mainly moved code around and CI still passes.
2024-08-08 10:10:58 +02:00
Erik Seliger
889ed1d948
oidc: Don't require to run refresh on provider init (#64159)
This PR makes the calls to create the OIDC provider explicit, so that we don't need to implicitly need to call a Refresh method, even if we might end up not needing the `p.oidc`.
This is a start toward being able to create providers on the fly cheaply vs having a globally managed list of providers in memory.

We did call refresh everywhere we do now anyways to the best of my understanding, so a passive goroutine in the background to my best understanding didn't add a lot here.

Test plan: Auth with SAMS locally still works.
2024-08-08 10:09:27 +02:00
Robert Lin
05e96ba1c4
fix/enterpriseportal/importer: disable query tracing when importing (#64352)
This can generate 10k+ spans in production

Also added simple handling for `pgx.NamedArgs` here, since I notice
those are missing

## Test plan

CI
2024-08-07 23:14:02 +00:00
Noah S-C
addba96f47
Revert "refactor: upgrade to rules_oci 2.0 (2nd attempt)" (#64351)
Reverts sourcegraph/sourcegraph#63829

Not working with Aspect Delivery

## Test plan

CI
2024-08-07 22:15:21 +00:00
Greg Magolan
be015c58c2
refactor: upgrade to rules_oci 2.0 (2nd attempt) (#63829)
2nd attempt of #63111, a follow up
https://github.com/sourcegraph/sourcegraph/pull/63085

rules_oci 2.0 brings a lot of performance improvement around oci_image
and oci_pull, which will benefit Sourcegraph. It will also make RBE
faster and have less load on remote cache.

However, 2.0 makes some breaking changes like

- oci_tarball's default output is no longer a tarball
- oci_image no longer compresses layers that are uncompressed, somebody
has to make sure all `pkg_tar` targets have a `compression` attribute
set to compress it beforehand.
- there is no curl fallback, but this is fine for sourcegraph as it
already uses bazel 7.1.

I checked all targets that use oci_tarball as much as i could to make
sure nothing depends on the default tarball output of oci_tarball. there
was one target which used the default output which i put a TODO for
somebody else (somebody who is more on top of the repo) to tackle
**later**.

## Test plan

CI. Also run delivery on this PR (don't land those changes)

---------

Co-authored-by: Noah Santschi-Cooney <noah@santschi-cooney.ch>
2024-08-07 22:21:49 +01:00
Robert Lin
24ab5292bf
fix/enterpriseportal/importer: import all subscriptions (#64348)
Turns out, the `dev` tag is not a reliable indicator of whether a
license is for dev use only - let's just import all subscriptions into
prod, and drop the customer records from dev later.

## Test plan

CI
2024-08-07 21:08:07 +00:00
Robert Lin
72f88adc15
fix/enterpriseportal/importer: make generated display name more unique (#64346)
Several subscriptions, upon import, ran into conflicts even with the
username - user display name - date format.


https://sourcegraph.sentry.io/issues/5688073768/?referrer=slack&notification_uuid=83d264fb-364a-4bc1-a5ab-9d7164a906cd&alert_rule_id=15193465&alert_type=issue

## Test plan

unit tests
2024-08-07 20:24:52 +00:00
Robert Lin
eedc12e789
feat/enterpriseportal: import data from dotcom (#63858)
Adds a background job that can periodically import subscriptions,
licenses, and Cody Gateway access from dotcom.

Note that subscriptions and licenses cannot be deleted, so we don't need
to worry about that. Additionally licenses cannot be updated, so we only
need to worry about creation and revocation.

The importer can be configured with `DOTCOM_IMPORT_INTERVAL` - if zero,
the importer is disabled.

Closes https://linear.app/sourcegraph/issue/CORE-216
## Test plan

```
DOTCOM_IMPORT_INTERVAL=10s sg start dotcom
```

Look for `service.importer` logs. Play around in
https://sourcegraph.test:3443/site-admin/dotcom/product/subscriptions/
to create and edit subscriptions, licenses, and Cody Gateway access.
Watch them show up in the database:

```
psql -d sourcegraph
sourcegraph# select * from enterprise_portal_susbscriptions;
sourcegraph# select * from enterprise_portal_susbscription_licenses;
sourcegraph# select * from enterprise_portal_cody_gateway_access;
```

---------

Co-authored-by: James Cotter <35706755+jac@users.noreply.github.com>
2024-08-07 11:44:18 -07:00
Camden Cheek
993e732583
Svelte: enable toggle by default (#64340) 2024-08-07 15:38:25 +00:00
Varun Gandhi
930033ca9b
chore: Replace QueuedCount -> CountByState with bitset parameter (#64302)
Previously, the QueuedCount method was confusing because:

1. By default, it actually returned the count for both the 'queued' and
   'errored' states (despite the name just have 'Queued').
2. There was an additional boolean flag for also returning entries in
    the 'processing' state, but reduced clarity at call-sites.

So I've changed the method to take a bitset instead, mirroring the
just-added Exists API, and renamed the method to a more
generic 'CountByState'.

While this does make call-sites a bit more verbose, I think the
clarity win makes the change an overall positive one.
2024-08-07 16:09:18 +08:00