Commit Graph

508 Commits

Author SHA1 Message Date
Keegan Carruthers-Smith
e332124698
servicecatalog: remove searcher dep on database (#64247)
Searcher doesn't speak to the database nor has it for a long time. See
https://github.com/sourcegraph/sourcegraph/pull/61463

Test Plan: The following command is empty

  go run ./dev/depgraph/ summary internal/database | grep 'cmd/searcher'
2024-08-05 09:55:49 +02:00
Matthew Manela
772e149729
feat(search): Add support to all Apex language extensions (#64194)
Part of
[GRAPH-759](https://linear.app/sourcegraph/issue/GRAPH-759/issue-with-apex-extension-not-appearing-for-langapex)

Linguist only supports a subset of the file extensions often used for
the Apex programming languages. This PR adds support for the main set
commonly used.

**Key changes**
1. Adds all extensions for Apex
2. Update our logic to handle multiple extensions for one language
3. Update tests to ensure we only manually map languages if they don't
exist OR have different extensions in go-enry (prevents us from
duplicating entries completely from go-enry)

## Test plan
- [x] Update unit tests
- [x] Validate locally by testing the language filter
2024-08-01 10:58:59 -04:00
Stefan Hengl
d3528061cd
chore(worker): move llm token counter to worker (#64008)
This moves the LLM token counter from `frontend` to the `worker`.

Test plan:
new unit test
2024-07-24 10:03:33 +02:00
Varun Gandhi
a6b6844678
chore: Rename Index -> AutoIndexJob (#63955)
Also renames a bunch of related types such as
- config.IndexJob -> config.AutoIndexJobSpec
- IndexLoader -> AutoIndexJobLoader

and so on.
2024-07-22 22:18:40 +08:00
Varun Gandhi
a5dad3b3a2
chore: Rename URI -> DocumentPath (#63979)
If you look at the code for `bulkMonikerResultsQuery` and
`minimalBulkMonikerResultsQuery`, you'll see that the last
returned value is the `document_path`. The value returned
was directly used an `UploadRootRelPath` elsewhere. So it
makes sense to rename the field from URI to `DocumentPath`.

## Test plan

Covered by existing tests
2024-07-22 15:11:49 +02:00
Robert Lin
d73e4639b0
fix/frontend/httpapi: improve request reader (#63923) 2024-07-19 19:10:41 +01:00
Robert Lin
920665ad44
chore/lib/telemetrygateway: fixup Dial helper (#63862)
Makes it a little easier to use

## Test plan

n/a
2024-07-16 20:38:53 +00:00
Robert Lin
2b3333aead
feat/lib/telemetrygateway: expose simple Dial (#63810)
For simple, MVP integrations with Telemetry Gateway, and also as a
reference. See example - this can be consumed with:

```go
import telemetrygatewayv1 "github.com/sourcegraph/sourcegraph/lib/telemetrygateway/v1"
```

## Test plan

n/a
2024-07-15 10:45:10 -07:00
Robert Lin
857d5200b3
feat/dotcom: use Enterprise Portal for Cody Gateway usage (#63653)
Closes https://linear.app/sourcegraph/issue/CORE-211

See https://linear.app/sourcegraph/issue/CORE-100 for a higher-level
view - this is the first proof-of-concept for achieving our migration
strategy to extract Enterprise subscription data out of dotcom while
retaining the existing UI until a future project ships a dedicated
Enterprise Portal UI
(https://linear.app/sourcegraph/project/kr-p-enterprise-portal-user-interface-dadd5ff28bd8).

The integration uses generated ConnectRPC client code + `react-query`,
the latter of which has already been used elsewhere for SSC
integrations. This is partly supported by
https://github.com/connectrpc/connect-query-es which offers
mostly-first-class integration with `react-query`, but I had to do some
fenangling to provide the query clients directly as I can't get the
React provider thing to work. The ConnectRPC clients point to the
proxies introduced in
https://github.com/sourcegraph/sourcegraph/pull/63652 which
authenticates the requests for Enterprise Portal, until we ship
https://linear.app/sourcegraph/project/kr-p1-streamlined-role-assignment-via-sams-and-entitle-2f118b3f9d4c/overview

## Test plan

### Local

First, `sg start dotcom`

Choose a subscription you have locally. Use `psql -d sourcegraph` to
connect to local database, then:

```
sourcegraph=# delete from product_licenses where product_subscription_id = '<local subscription ID>';
DELETE 1
sourcegraph=# update product_subscriptions set id = '58b95c21-c2d0-4b4b-8b15-bf1b926d3557' where id = '<local subscription ID>';
UPDATE 1
```

Now annoyingly the UI will break because there is no license, we need:

```gql
query getGraphQLID {
  dotcom {
    productSubscription(uuid:"58b95c21-c2d0-4b4b-8b15-bf1b926d3557") {
      id # graphQL ID
    }
  }
}

mutation createLicense {
  dotcom {
    generateProductLicenseForSubscription(productSubscriptionID:"<graphQLID>", license:{
      tags:["dev"]
      userCount:100
      expiresAt:1814815397
    }) {
      id
    }
  }
}
```

This effectively lets us have a "pretend S2" subscription locally.
Visiting the subscription page now at
https://sourcegraph.test:3443/site-admin/dotcom/product/subscriptions/58b95c21-c2d0-4b4b-8b15-bf1b926d3557


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/1e77d77d-8032-436b-ab1d-393b34e8e4b5)

The data matches the "real" data currently at
https://sourcegraph.com/site-admin/dotcom/product/subscriptions/58b95c21-c2d0-4b4b-8b15-bf1b926d3557

### Against dotcom

```
sg start web-standalone
```

follow
https://www.loom.com/share/6cb3b3ca475b4b9392aa4b11938e76e6?sid=6cd1a689-d75d-4133-bcff-b0c7d25b23f1
and then check out some product subscriptions
2024-07-10 19:22:08 +00:00
Robert Lin
7d91894a01
chore/otel-collector: upgrade to v0.103.0, remove jaegerexporter (#63171)
Thread:
https://sourcegraph.slack.com/archives/C1JH2BEHZ/p1717797870638299

One problem caused by this upgrade is that the [deprecated
`jaegerexporter`](https://github.com/open-telemetry/opentelemetry-specification/pull/2858)
no longer builds at all with the last published version, so for the
upgrade to go through it must be removed. I've updated local `sg start`
to work with this change, but some Release team support is needed for
deployment configuration + customer-facing docs changes:
https://sourcegraph.slack.com/archives/C1JH2BEHZ/p1718143249191349?thread_ts=1717797870.638299&cid=C1JH2BEHZ,
since current guidance asks customers to configure `jaegerexporter`.

Part of https://linear.app/sourcegraph/issue/SEC-1680

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

## Test plan

Followed steps shared in
https://sourcegraph.slack.com/archives/C04MYFW01NV/p1718136211292469 to
run locally, since `sg run jaeger otel-collector` alone is insufficient
to get updated images:

```diff
diff --git a/wolfi-images/opentelemetry-collector.yaml b/wolfi-images/opentelemetry-collector.yaml
index b995a3d531b..76de80d4f84 100644
--- a/wolfi-images/opentelemetry-collector.yaml
+++ b/wolfi-images/opentelemetry-collector.yaml
@@ -7,7 +7,11 @@ contents:
     - mailcap
 
     ## opentelemetry-collector packages
-    - opentelemetry-collector@sourcegraph
+    - opentelemetry-collector@branch
+  keyring:
+    - https://packages.sgdev.org/sourcegraph-melange-dev.rsa.pub
+  repositories:
+    - '@branch https://packages.sgdev.org/branches/otel-collector-upgrade'
 
 paths:
   - path: /otel-collector
```

plus `sg wolfi lock opentelemetry-collector` will make `sg run
otel-collector` use the correct image.

**The above diffs SHOULD NOT be committed. The lock should happen
post-merge.**

Spot-checked some traces locally with:

```
sg run jaeger otel-collector
sg start
```


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/dff88d5a-db9a-4039-b7ba-682e120bdc41)


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/7e553894-0026-47de-ae38-ba5502b94c63)


## Changelog 

- OpenTelemetry Collector: Upgraded OpenTelemetry Collector to v0.103.0
- OpenTelemetry Collector: The [deprecated `jaegerexporter` has been
removed](https://github.com/open-telemetry/opentelemetry-specification/pull/2858).
Users of `exporter: { jaeger: ... }` in the OpenTelemetry Collector
should use `exporter: { otlp/jaeger: ... }` to send traces directly to
Jaeger via its OTLP receiver.
- Users of the default Jaeger configurations now need to provide
`JAEGER_OTLP_GRPC_PORT` as well as the existing `JAEGER_HOST`
configuration.

---------

Co-authored-by: Anish Lakhwara <anish+github@lakhwara.com>
Co-authored-by: Anish Lakhwara <anish+git@lakhwara.com>
2024-07-10 09:01:41 -07:00
Robert Lin
28f797e866
feat/enterpriseportal: database layer for subscriptions upsert (#63703)
Implements upsert for all the subscriptions fields in the DB client. As
part of this I generalized the logic for building upsert DB interactions
into a new `upsert` package, because this pattern is a common one we'll
need to implement to maintain various AIP-update-compliant endpoints,
which specifies various upsert behaviours: https://google.aip.dev/134

Part of CORE-216
Part of CORE-156

## Test plan

Integration tests against DB
2024-07-09 14:35:00 -07:00
Stefan Hengl
1af563b614
batches: use "keyword" as default pattern type (#63613)
This is part of the Keyword GA Project.

Batch Changes uses Sourcegraph queries to define the list of repositories on which the batch change will run.

With this change we default to pattern type "keyword" instead of "standard". 

To make this a backward compatible change, we also introduce a version identifier to batch specs. Authors can specify `version: 2` in the spec, in which case we default to pattern type "keyword". Existing specs (without a specified version) and specs with `version: 1` will keep using pattern type "standard".

Notes:
- Corresponding doc update [PR](https://github.com/sourcegraph/docs/pull/477)
- We don't have a query input field, but instead the query is defined in a batch spec YAML. It didn't feel right to edit the YAML and append "patternType: " on save, which is what we do for Code Monitors and Insights.
- I misuse the pattern type query parameter to effectively override the version. Once we introduce "V4" we should come back here and clean up. I left a TODO in the code.

Test plan:
- New and updated unit tests
- manual testing
  - new batch changes use `version: 2` by default.
  - using an unsupported version returns an error
  - I ran various "on:" queries to verify that version 2 uses keyword search and version 1 uses standard search.
2024-07-09 10:35:01 +02:00
Jean-Hadrien Chabran
2dfeb486d5
fix(local): fix race in sg_start_test.go (#63642)
Fixes DINF-82; This was very much a rabbithole. A few things: 

- The race that @bobheadxi mentioned here
https://github.com/sourcegraph/sourcegraph/pull/63405#discussion_r1648180713
wasn't from `*output.Output` being unsafe, but `outputtest.Buffer` as it
happened again (see
[DINF-82](https://linear.app/sourcegraph/issue/DINF-82/devsgsg-test-failed-with-a-detected-race-condition))
- There something messed up with `cmds.start()`, which sometimes ends up
printing the command output _after_ the exit message instead of before.
- The crude `sort.Strings(want|have)` that was there already fixes that.
- And without the sleep, it's possible to read the output from the
`outputtest.Buffer` before the command outputs get written to it.
- The `time.Sleep(300 * time.Milliseconds)` _mitigates/hides_ that
problem.

At least, this shouldn't blow up in CI and buys us time to fix the whole
thing. We're tracking this in DINF-104. And out of 200 runs, I also
stumbled on a race in `progress_tty`, tracked in DINF-105 (that packages
is originally meant to be used by `src-cli` and was re-used for `sg` 3
years ago).

I'm pretty unhappy about the solution, but a bandage is better than
nothing. While ideally, we should really reconsider dropping
`std.Output` entirely in `sg` and use the good stuff from
github.com/charmbracelet instead because we don't want to spend too much
time on arcane terminal things ourselves, I'm much more about concerned
the concurrency issues mentioned above.

## Test plan

CI + `sg bazel test //dev/sg:sg_test --runs_per_test=100`
2024-07-04 19:11:10 +02:00
Robert Lin
e24464b3af
feat/enterpriseportal: define GetCodyGatewayUsage RPC, use uint64 for rate limits (#63531)
Part of https://linear.app/sourcegraph/issue/CORE-201. The RPC will be
backed by https://github.com/sourcegraph/sourcegraph/pull/63528

The `uint64` for ratelimits is a backwards-compatible change, per proto
docs:

> int32, uint32, int64, uint64, and bool are all compatible – this means
you can change a field from one of these types to another without
breaking forwards- or backwards-compatibility.

## Test plan

CI
2024-07-02 09:25:23 -07:00
Robert Lin
f5afeb8c22
feat/enterpriseportal: make UpdateEnterpriseSubscriptionMembership authoritative (#63502)
Closes https://linear.app/sourcegraph/issue/CORE-199. AIP generally
implies `Update` RPCs are authoritative, which means that we should be
deleting all roles memberships not provided to
`UpdateEnterpriseSubscriptionMembership`. Most important outcome here is
that we can actually remove roles from users by assigning them an empty
role set `[]`

Later we can add a "get roles" RPC to safely make these updates, and
introduce a purely additive RPC if needed. It's not a huge deal right
now because we only have 1 role ("customer admin")

Also removes the deprecated value from
https://github.com/sourcegraph/sourcegraph/pull/63501.

## Test plan

Unit tests, expanded with better table-driven cases and expanded
assertions
2024-06-27 12:52:46 -07:00
Robert Lin
ddb1d9a538
chore/enterpriseportal: rename customer admin role in API (#63501)
Studying Joe's work a bit more in depth I noticed that our API
representation of this role ("Cody Analytics admin") does not line up
with our internal representation ("customer admin").

Since we're already here, it's probably better to just align on
"customer admin" as the role everywhere, and figure out more granular
roles if we need it later.

Once it's rolled out and usages are migrated
(https://github.com/sourcegraph/cody-analytics/pull/83), we can remove
the deprecated enum entirely
(https://github.com/sourcegraph/sourcegraph/pull/63502)

## Test plan

CI
2024-06-27 10:12:49 -07:00
James Cotter
ea9c45df8f
msp/runtime: split contract into JobContract and ServiceContract (#63494)
Splits the runtime contract into a JobContract and ServiceContract.
This lets better handle initialisation such as env vars which is
conditional depending on the contract type.
## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
ci
2024-06-26 19:46:10 +00:00
Robert Lin
ffddca87ea
chore/enterpriseportal: propagate context to migration database context (#63455)
Follow-up to #63448 - we now get Redis spans, but not the database
operations that happen throughout a migration. Maybe this will do the
thing?

## Test plan

n/a
2024-06-25 01:18:15 +00:00
Robert Lin
ef50a04562
chore/enterpriseportal: tweak maybeMigrate tracing (#63448)
Fix an issue with context propagation and add a little more detail on
automigration steps

## Test plan

CI
2024-06-24 14:07:44 -07:00
Varun Gandhi
34b54c9f8d
chore(codeintel): Differentiate between paths relative to upload root vs repo root (#63437)
The use of different types makes it clear which kind of path is needed
in which place. This also makes the CodeNavService layering clearer;
it has the responsibility of taking in RepoRelPaths and correctly interfacing
with LsifStore, which deals in UploadRelPath values.
2024-06-24 20:27:26 +08:00
Joe Chen
ef73ae65ab
lib/msp: downgrade GORM to 1.25.6 (#63427)
Trying to address


![CleanShot 2024-06-21 at 20 25
19@2x](https://github.com/sourcegraph/sourcegraph/assets/2946214/4bbce267-6b30-4a61-8981-759924ccb7b3)

GORM often gives no shit about versioning compatibility and may break
things, let's downgrade the known good version first.
2024-06-22 00:34:01 +00:00
Robert Lin
cb3a1e4dc8
feat/sg: add 'sg enterprise' commands for Cody Analytics (#63414)
Closes CORE-194 - added a bit more than strictly needed here, but this
PR adds:

- `sg enterprise subscription list`
- `sg enterprise subscription set-instance-domain`
- `sg enterprise update-membership`
- `sg enterprise license list`

## Test plan

<img width="1055" alt="image"
src="https://github.com/sourcegraph/sourcegraph/assets/23356519/48ec40b0-fbac-4513-9ad8-fc3174774ada">


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/806fd054-806b-4ecb-a969-32900112f368)
2024-06-21 16:29:31 -07:00
Robert Lin
5770f30389
feat/enterpriseportal: validate and normalize instance domains (#63415)
Validates domains on update (subscription and member) to ensure that we
don't get anything too wonky.

## Test plan

Tests
2024-06-21 16:14:23 -07:00
Robert Lin
78622cbe6c
chore/enterpriseportal: only use 'revoke' verb for licenses (#63407)
There's a confusing notion of "archived license" that really means
"archived subscription", which is problematic because "can an archived
subscription, have valid licenses, in a world where revoked licenses
exist?"

IMO archiving a subscription should immediately and permanently revoke
all its associated licenses, per discussion in
https://github.com/sourcegraph/sourcegraph/pull/63330#discussion_r1645333457.
This means we can remove all notion of "archived license" - when looking
at licenses, they're only revoked, or not revoked.

⚠️ These RPCs are not used anywhere yet so this is a safe breaking
change.

## Test plan

CI
2024-06-20 16:35:31 -07:00
Robert Lin
78dcd57221
fix/sg: fix mangled log output from sg start and sg run (#63405)
Right now `sg run` / `sg start` can horribly mangle multi-line output. A
nicely annotated report from @unknwon:


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/38acbaf9-89dc-4d4b-9fd7-b601f5654240)

Replacing the "buffered process logger" thing with
https://github.com/bobheadxi/streamline which powers `sourcegraph/run`
etc (fairly reliably if I do say so myself) fixes this for a few cases
where I can reliably repro wonky misordered output 😁

## Test plan

`sg start dotcom` with `sg.config.overwrite.yaml`:

```yaml
commands:
  enterprise-portal:
    env:
      SRC_LOG_LEVEL: debug
      PG_QUERY_LOGGING: true
```

Log scope `pgx.devtracer` is consistently formatted  , even with high
volume of logs


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/5c46f94f-e388-477a-94d3-151d5a3c7468)

Also don't see anything suspicious happening after running for a while
2024-06-20 16:07:27 -07:00
James Cotter
472a5562c3
msp/runtime: add GetFloat to runtime Env (#63399)
The runtime `Env` currently lacks a convenient method for getting a
floating point env var. This PR adds a `GetFloat`method which will parse
a float64 from a given env var

Part of CORE-181
## Test plan
locally tested 
values such as `10.2` and `infinity` were correctly parsed
2024-06-20 18:38:11 +01:00
Varun Gandhi
0505269d54
chore: Bump go-enry and Zoekt to handle new languages (#63281)
- Updates enry to include languages from Linguist v7.29.0 such as Mojo etc.
- Updates auto-complete filters in frontend code.
- Updates Zoekt to pick up newer version with bumped enry dep.
- Updates language extension overrides to avoid ambiguity for `.json` and `.yml`.
- Updates snapshot tests.
2024-06-20 22:19:39 +08:00
Joe Chen
b717fd518a
enterprise-portal: implement basic MSP IAM and RPCs (#63173)
Closes CORE-99, closes CORE-176

This PR is based off (and was also served as PoC of) [RFC 962: MSP IAM
framework](https://docs.google.com/document/d/1ItJlQnpR5AHbrfAholZqjH8-8dPF1iQcKh99gE6SSjs/edit).
It comes with two main parts:

1. The initial version of the MSP IAM SDK:
`lib/managedservicesplatform/iam`
- Embeds the [OpenFGA server
implementation](https://github.com/openfga/openfga/tree/main/pkg/server)
and exposes the a `ClientV1` for interacting with it.
- Automagically manages the both MSP IAM's and OpenFGA's database
migrations upon initializing the `ClientV1`.
![CleanShot 2024-06-18 at 15 09
24@2x](https://github.com/sourcegraph/sourcegraph/assets/2946214/387e0e28-a6c2-4664-b946-0ea4a1dd0804)
- Ensures the specified OpenFGA's store and automatization model DSL
exists.
- Utility types and helpers to avoid easy mistakes (i.e. make the
relation tuples a bit more strongly-typed).
- Decided to put all types and pre-defined values together to simulate a
"central registry" and acting as a forcing function for services to form
some sort of convention. Then when we migrate the OpenFGA server to a
separate standalone service, it will be less headache about
consolidating similar meaning types/relations but different string
literals.
1. The first use case of the MSP IAM:
`cmd/enterprise-portal/internal/subscriptionsservice`
	- Added/updated RPCs:
		- Listing enterprise subscriptions via permissions
		- Update enterprise subscriptions to assign instance domains
- Update enterprise subscriptions membership to assign roles (and
permissions)
- A database table for enterprise subscriptions, only storing the extra
instance domains as Enterprise Portal is not the
writeable-source-of-truth.

## Other minor changes

- Moved `internal/redislock` to `lib/redislock` to be used in MSP IAM
SDK.
- Call `createdb ...` as part of `enterprise-portal` install script in
`sg.config.yaml` (`msp_iam` database is a hard requirement of MSP IAM
framework).

## Test plan

Tested with gRPC UI:

- `UpdateEnterpriseSubscription` to assign an instance domain
- `UpdateEnterpriseSubscriptionMembership` to assign roles
- `ListEnterpriseSubscriptions`:
	- List by subscription ID
	- List by instance domain
	- List by view cody analytics permissions

---------

Co-authored-by: Robert Lin <robert@bobheadxi.dev>
2024-06-19 21:46:48 -04:00
Robert Lin
3a87f3278b
feat/enterpriseportal: ArchiveEnterpriseSubscription RPC definition (#63330)
Enterprise Portal equivalent of the `archiveProductSubscription` GraphQL
mutation. It's not a "delete" operation - we retain the record forever -
so it's idempotent, as an archive on an already-archived subscription
can return OK. If we want to add a hard delete we should add a separate
one based more closely on https://google.aip.dev/135.

It's not part of "update" because it's closer to a "delete" than
anything else, and currently cannot be undone.

Closes CORE-153

## Test plan

CI
2024-06-19 13:17:47 -07:00
Robert Lin
8c14a8c4a4
feat/enterpriseportal: RevokeEnterpriseSubscriptionLicense RPC definition (#63331)
Enterprise Portal equivalent of the `revokeLicense` GraphQL mutation.
It's not a "delete" operation - we currently retain the record forever -
so it's idempotent, as the revocation of an already-revoked license can
return OK. If we want to add a hard delete we should add a separate one
based more closely on https://google.aip.dev/135.

Related: https://github.com/sourcegraph/sourcegraph/pull/63330

Closes CORE-153

## Test plan

CI
2024-06-19 13:04:10 -07:00
Robert Lin
a6cacec487
feat/enterpriseportal: CreateEnterpriseSubscriptionLicense RPC defininition (#63323)
Defines an RPC for creating licenses for a subscription in Enterprise
Portal (which will replace the existing
`generateProductLicenseForSubscription` GraphQL mutation). Because of
#63317 we will no longer accept Salesforce details as part of the input
for creating licenses. Most everything else stays the same.

https://google.aip.dev/133 says we must name the parent subscription ID
as the `parent` parameter. But, we already have a `subscription_id` in
`EnterpriseSubscriptionLicense`, which feels more descriptive, so I've
opted not to use `parent`... but I'm open to suggestions otherwise 🤷

Closes CORE-150, implementation tracked in CORE-157

## Test plan

CI
2024-06-18 17:41:14 -07:00
Robert Lin
a333771bd4
feat/enterpriseportal: add Salesforce metadata at subscription level (#63317)
Today Salesforce "subscription ID" and "opportunity ID" are attached at
the license level. They should really be on the Enterprise subscription
level instead, which are parent entities of licenses. As we move forward
with CORE-149, I think this is a good chance to introduce this change in
our schema, and migrate the currently per-license information to the
subscription level when we move things into Enterprise Portal.

## Test plan

CI
2024-06-18 13:39:16 -07:00
Robert Lin
e4bff7c176
feat/enterpriseportal: CreateEnterpriseSubscription RPC definition (#63308)
Proposed RPC definition for creating an Enterprise Subscription, which
is currently the `createProductSubscription` GraphQL mutation, via
Enterprise Portal. The RPC follows patterns suggested for "create" RPCs
in https://google.aip.dev/133.

One thing we didn't account for yet is the way AIP suggests handling IDs
and names. It raises some interesting points about user-provided ID
components in https://google.aip.dev/133#user-specified-ids - I'm pretty
sure we don't want to introduce a user-controlled component to the
currently randomized subscription ID, _but_ we may want to introduce a
"slug" identifier of sorts that must be unique. The default value can
use something like https://pkg.go.dev/github.com/gosimple/slug to
convert the display name. This would help us ensure duplicate
subscriptions for the same customer aren't created.

Closes CORE-149. Implementation is tracked in a follow-up (CORE-155) -
for now this will just return "unimplemented".

## Test plan

CI
2024-06-18 12:35:25 -07:00
Robert Lin
d0ea29215f
feat/enterpriseportal: UpdateCodyGatewayAccess RPC definition (#63307)
Proposed RPC definition for updating Cody Gateway access, which is
currently part of the `updateProductSubscription` GraphQL mutation, via
Enterprise Portal. The RPC follows patterns suggested for "update" RPCs
in https://google.aip.dev/134.

As an example, to use `UpdateCodyGatewayAccess` to update a
subscription's code completions limit:

```ts
UpdateCodyGatewayAccess({
  access: {
    subscription_id: "es_...",
    code_completions: { limit: 420 },
  },
  update_mask: {
    paths: ["code_completions.limit"],
  },
})  
```

Closes CORE-154. Implementation is tracked in a follow-up (CORE-159) -
for now this will just return "unimplemented".

I've also removed the "draft state" docstrings.

## Test plan

CI
2024-06-18 12:24:00 -07:00
Varun Gandhi
3437f8253d
chore: Centralize languages package as source-of-truth (#63292)
This patch does a few things:

- Adds `go-enry` packages to depguard, so that people do not
  accidentally use enry APIs instead of the corresponding APIs
  in the `languages` package.
- Adds more tests for different functions in the languages package
  to ensure mutual consistency in how language<->extension mappings
  are handled.
- Adds tests for enry upgrades
- Adds comments with IDs so that related parts in the code can be
   pieced together easily
2024-06-18 13:10:24 +00:00
Varun Gandhi
b4ddf9c04d
chore: Add more tests for GetLanguages API (#63260)
Adds clearer documentation for return values and some property-based tests
2024-06-14 10:07:52 +08:00
James Cotter
4bafd037e5
internal/telemetry: make adding EventsStore middleware easier (#63216)
Refactors usage of teestore to use new default `telemetry.EventsStore`
constructor. Default middleware can be added to the constructor to more
easily make transformations to server side generated events.

Closes CORE-123
## Test plan
CI
2024-06-13 11:55:06 +01:00
Robert Lin
42d7ba736e
feat/msp/runtime: PG_QUERY_LOGGING=true for local dev query logging (#63164)
Closes https://linear.app/sourcegraph/issue/CORE-168

## Test plan

```
[enterprise-...l] DEBUG pgx.devtracer.enterprise-portal contract/postgresql.go:157 pgx.QueryStart
[enterprise-...l] ---
[enterprise-...l] SELECT count(*) FROM pg_indexes WHERE tablename = $1 AND indexname = $2 AND schemaname = CURRENT_SCHEMA()
[enterprise-...l] ---
[enterprise-...l]  {"args": ["{\"1082\":1,\"1114\":1,\"1184\":1,\"16\":1,\"17\":1,\"20\":1,\"21\":1,\"23\":1,\"26\":1,\"28\":1,\"29\":1,\"700\":1,\"701\":1}", "\"permissions\"", "\"idx_permissions_namespace\""]}
[enterprise-...l] DEBUG pgx.devtracer.enterprise-portal contract/postgresql.go:163 pgx.QueryEnd {"commandTag": "SELECT 1", "error": "<nil>"}
[enterprise-...l] DEBUG pgx.devtracer.enterprise-portal contract/postgresql.go:157 pgx.QueryStart
[enterprise-...l] ---
[enterprise-...l] SELECT count(*) FROM pg_indexes WHERE tablename = $1 AND indexname = $2 AND schemaname = CURRENT_SCHEMA()
[enterprise-...l] ---
[enterprise-...l]  {"args": ["{\"1082\":1,\"1114\":1,\"1184\":1,\"16\":1,\"17\":1,\"20\":1,\"21\":1,\"23\":1,\"26\":1,\"28\":1,\"29\":1,\"700\":1,\"701\":1}", "\"permissions\"", "\"idx_permissions_subject\""]}
```

## Changelog

- MSP runtime users can now set `PG_QUERY_LOGGING=true` to dump queries
and arguments from database interactions at `DEBUG` level in local dev.
2024-06-11 11:01:30 -07:00
Matthew Manela
949a538654
feat(search): Support Magik language file filter in search (#63110)
Adds support to the lang file filter for Magik language (`lang: Magik`).
In order to do that we add wrappers around go-enry and update search
code to use them. This provides flexibility for us in the future to
support other languages that are not in Linguist as well.
2024-06-11 13:41:39 -04:00
Vincent
add4baa455
chore(security): update dependencies (#63197)
This PR upgrades a bunch of Golang dependencies that have known security
issues.

## Test plan
CI tests, ran `sg start`.
2024-06-11 16:14:24 +01:00
Robert Lin
7e9d8ec8dc
feat/cody-gateway: use Enterprise Portal for actor/productsubscriptions (#62934)
Migrates Cody Gateway to use the new Enterprise Portal's "read-only"
APIs. For the most part, this is an in-place replacement - a lot of the
diff is in testing and minor changes. Some changes, such as the removal
of model allowlists, were made down the PR stack in
https://github.com/sourcegraph/sourcegraph/pull/62911.

At a high level, we replace the data requested by
`cmd/cody-gateway/internal/dotcom/operations.graphql` and replace it
with Enterprise Portal RPCs:

- `codyaccessv1.GetCodyGatewayAccess`
- `codyaccessv1.ListCodyGatewayAccesses`

Use cases that previously required retrieving the active license tags
now:

1. Use the display name provided by the Cody Access API
https://github.com/sourcegraph/sourcegraph/pull/62968
2. Depend on the connected Enterprise Portal dev instance to only return
dev subscriptions https://github.com/sourcegraph/sourcegraph/pull/62966

Closes https://linear.app/sourcegraph/issue/CORE-98
Related to https://linear.app/sourcegraph/issue/CORE-135
(https://github.com/sourcegraph/sourcegraph/pull/62909,
https://github.com/sourcegraph/sourcegraph/pull/62911)
Related to https://linear.app/sourcegraph/issue/CORE-97

## Local development

This change also adds Enterprise Portal to `sg start dotcom`. For local
development, we set up Cody Gateway to connect to Enterprise Portal such
that zero configuration is needed - all the required secrets are sourced
from the `sourcegrah-local-dev` GCP project automatically when you run
`sg start dotcom`, and local Cody Gateway will talk to local Enterprise
Portal to do the Enterprise subscriptions sync.

This is actually an upgrade from the current experience where you need
to provide Cody Gateway a Sourcegraph user access token to test
Enterprise locally, though the Sourcegraph user access token is still
required for the PLG actor source.

The credential is configured in
https://console.cloud.google.com/security/secret-manager/secret/SG_LOCAL_DEV_SAMS_CLIENT_SECRET/overview?project=sourcegraph-local-dev,
and I've included documentation in the secret annotation about what it
is for and what to do with it:


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/c61ad4e0-3b75-408d-a930-076a414336fb)

## Rollout plan

I will open PRs to set up the necessary configuration for Cody Gateway
dev and prod. Once reviews taper down I'll cut an image from this branch
and deploy it to Cody Gateway dev, and monitor it closely + do some
manual testing. Once verified, I'll land this change and monitor a
rollout to production.

Cody Gateway dev SAMS client:
https://github.com/sourcegraph/infrastructure/pull/6108
Cody Gateway prod SAMS client update (this one already exists):

```
accounts=> UPDATE idp_clients
SET scopes = scopes || '["enterprise_portal::subscription::read", "enterprise_portal::codyaccess::read"]'::jsonb
WHERE id = 'sams_cid_018ea062-479e-7342-9473-66645e616cbf';
UPDATE 1
accounts=> select name, scopes from idp_clients WHERE name = 'Cody Gateway (prod)';
        name         |                                                              scopes                                                              
---------------------+----------------------------------------------------------------------------------------------------------------------------------
 Cody Gateway (prod) | ["openid", "profile", "email", "offline_access", "enterprise_portal::subscription::read", "enterprise_portal::codyaccess::read"]
(1 row)
```

Configuring the target Enterprise Portal instances:
https://github.com/sourcegraph/infrastructure/pull/6127

## Test plan

Start the new `dotcom` runset, now including Enterprise Portal, and
observe logs from both `enterprise-portal` and `cody-gateway`:

```
sg start dotcom
```

I reused the test plan from
https://github.com/sourcegraph/sourcegraph/pull/62911: set up Cody
Gateway external dependency secrets, then set up an enterprise
subscription + license with a high seat count (for a high quota), and
force a Cody Gateway sync:

```
curl -v -H 'Authorization: bearer sekret' http://localhost:9992/-/actor/sync-all-sources
```

This should indicate the new sync against "local dotcom" fetches the
correct number of actors and whatnot.

Using the local enterprise subscription's access token, we run the QA
test suite:

```sh
$ bazel test --runs_per_test=2 --test_output=all //cmd/cody-gateway/qa:qa_test --test_env=E2E_GATEWAY_ENDPOINT=http://localhost:9992 --test_env=E2E_GATEWAY_TOKEN=$TOKEN
INFO: Analyzed target //cmd/cody-gateway/qa:qa_test (0 packages loaded, 0 targets configured).
INFO: From Testing //cmd/cody-gateway/qa:qa_test (run 1 of 2):
==================== Test output for //cmd/cody-gateway/qa:qa_test (run 1 of 2):
PASS
================================================================================
INFO: From Testing //cmd/cody-gateway/qa:qa_test (run 2 of 2):
==================== Test output for //cmd/cody-gateway/qa:qa_test (run 2 of 2):
PASS
================================================================================
INFO: Found 1 test target...
Target //cmd/cody-gateway/qa:qa_test up-to-date:
  bazel-bin/cmd/cody-gateway/qa/qa_test_/qa_test
Aspect @@rules_rust//rust/private:clippy.bzl%rust_clippy_aspect of //cmd/cody-gateway/qa:qa_test up-to-date (nothing to build)
Aspect @@rules_rust//rust/private:rustfmt.bzl%rustfmt_aspect of //cmd/cody-gateway/qa:qa_test up-to-date (nothing to build)
INFO: Elapsed time: 13.653s, Critical Path: 13.38s
INFO: 7 processes: 1 internal, 6 darwin-sandbox.
INFO: Build completed successfully, 7 total actions
//cmd/cody-gateway/qa:qa_test                                            PASSED in 11.7s
  Stats over 2 runs: max = 11.7s, min = 11.7s, avg = 11.7s, dev = 0.0s

Executed 1 out of 1 test: 1 test passes.
```
2024-06-07 11:46:01 -07:00
Varun Gandhi
1284536eed
chore(codenav): Resolve repo and commit in common code (#63072)
Adds logic to validate as much of the args to usagesForSymbols as possible.
Also adds some infrastructure for property-based testing.
2024-06-07 21:58:36 +08:00
Joe Chen
ce025a069a
enterprise-portal: init database schema and handler store (#63139)
Part of CORE-99

This PR scaffolds the database schema and code structure based on
[CORE-99
comment](https://linear.app/sourcegraph/issue/CORE-99/enterprise-portal-design-sams-user-to-subscription-rpcs#comment-8105ac31)
with some modifications. See inline comments for more elaborations.
- It uses GORM's ONLY for auto migration, just to kick things off, we
may migrate to file-based migration like we are planning for SAMS.
- It then uses the `*pgxpool.Pool` as the DB interface for executing
business logic queries.

Additionally, refactored `subscriptionsservice/v1.go` to use a `Store`
that provide single interface for accessing data(base), as we have been
doing in SAMS and SSC.

## Test plan

Enterprise Portal starts locally, and database is initialized:

![CleanShot 2024-06-06 at 17 02
42@2x](https://github.com/sourcegraph/sourcegraph/assets/2946214/f6cbc2bf-bd95-4691-9f87-b2450cc31e4d)
2024-06-06 18:54:12 -04:00
Matthew Manela
19ef2d973e
feat(search): Add Syntax Highlighting for Magik language (#62919)
Fixes GRAPH-621

 Add syntax highlighting for magik programming language
2024-06-06 16:49:07 -04:00
Joe Chen
c669fcf26e
enterprise-portal: rename "scope" to "permission" for query RPC (#63137)
Part of CORE-99

After some heavy discussion, we settled on "Roles + Permissions" (that
is a whole different large topic), but as far as the RPCs here
concerned, using "scopes" here is not appropriate.
2024-06-06 19:40:15 +00:00
Noah S-C
bb178ba729
chore(tooling): bump Go version to 1.22.4 (#63124)
Bump for @evict 

## Test plan

CI passes with no complaints

## Changelog

- Bumped version of Go used to build to 1.22.4
2024-06-06 15:19:03 +00:00
Varun Gandhi
2955bb6cfb
chore: Change errors.HasType to respect multi-errors (#63024)
With this patch, the `errors.HasType` API behaves similar to `Is` and `As`,
where it checks the full error tree instead of just checking a linearized version
of it, as cockroachdb/errors's `HasType` implementation does not respect
multi-errors.

As a consequence, a bunch of relationships between HasType and Is/As that
you'd intuitively expect to hold are now true; see changes to `invariants_test.go`.
2024-06-06 13:02:14 +00:00
Joe Chen
22e846a14e
enterprise-portal: update RPC for subscription domain and members (#63105)
Part of CORE-99

This PR adds new RPCs and fields for add and get/list subscription
domain and members, prepare to be used by Cody Analytics related
operations.
2024-06-05 21:32:08 -04:00
Robert Lin
2630d5fc56
chore/msp/runtime: add args as trace attributes, clean up tracing code (#63087)
This is a simplified version of what we have for in-Sourcegraph db
connections as well. They're not directly compatible because we use
`pgx` hooks.

## Test plan

n/a
2024-06-04 17:30:32 -07:00
Varun Gandhi
d7f3e542cf
chore: Replace errors.As with generic As and AsInterface (#63047)
Splits the signature of errors.As into two more specialized functions
which catch more errors at compile-time using generics.
2024-06-04 01:56:55 +00:00