Skip to content

Commit

Permalink
Revert "Revert "Serve config values for the frontend"" (BloopAI#260)
Browse files Browse the repository at this point in the history
* Revert "Revert "Serve config values for the frontend (BloopAI#257)" (BloopAI#259)"

This reverts commit 5786d61.

* remove unused sentry initialize function

* Change tauri target file name

* Fix formatting

* Oops, bad merge

* add answer api url to config in release workflow

---------

Co-authored-by: rsdy <[email protected]>
Co-authored-by: rsdy <[email protected]>
  • Loading branch information
3 people authored Mar 22, 2023
1 parent 9cae59f commit 280b33b
Show file tree
Hide file tree
Showing 20 changed files with 96 additions and 75 deletions.
11 changes: 3 additions & 8 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
ANALYTICS_FE_WRITE_KEY_PROD=
ANALYTICS_FE_WRITE_KEY_DEV=
ANALYTICS_DATA_PLANE_URL=
SENTRY_DSN_FE=
SENTRY_DSN_BE=
API_URL='optional'
DEVICE_ID='optional'
ONBOARDING=''
API_URL='required for self-serve only'
DEVICE_ID='used as user_id in analytics (for self-serve)'
ONBOARDING='if you want to force onboarding flow'

4 changes: 0 additions & 4 deletions .github/workflows/build-on-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ jobs:
awsRegion: ${{ secrets.AWS_REGION }}
awsAccountID: ${{ secrets.AWS_ACCOUNT_ID }}
slackBuildWebhook: ${{ secrets.SLACK_BUILD_WEBHOOK }}
build-args: |
ANALYTICS_FE_WRITE_KEY_PROD=${{ secrets.ANALYTICS_FE_WRITE_KEY_PROD }}
ANALYTICS_DATA_PLANE_URL=${{ secrets.ANALYTICS_DATA_PLANE_URL }}
SENTRY_DSN_FE=${{ secrets.SENTRY_DSN_FE }}

validate_helm:
uses: BloopAI/reusable-workflows/.github/workflows/validate-helm-chart.yml@main
Expand Down
4 changes: 0 additions & 4 deletions .github/workflows/build-on-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,3 @@ jobs:
awsRegion: ${{ secrets.AWS_REGION }}
awsAccountID: ${{ secrets.AWS_ACCOUNT_ID }}
slackBuildWebhook: ${{ secrets.SLACK_BUILD_WEBHOOK }}
build-args: |
ANALYTICS_FE_WRITE_KEY_PROD=${{ secrets.ANALYTICS_FE_WRITE_KEY_PROD }}
ANALYTICS_DATA_PLANE_URL=${{ secrets.ANALYTICS_DATA_PLANE_URL }}
SENTRY_DSN_FE=${{ secrets.SENTRY_DSN_FE }}
7 changes: 5 additions & 2 deletions .github/workflows/tauri-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@ jobs:
run: exit 1

- name: Set environment
run: echo "ANALYTICS_FE_WRITE_KEY_PROD=${{ secrets.ANALYTICS_FE_WRITE_KEY_PROD }}\nSENTRY_DSN_FE=${{ secrets.SENTRY_DSN_FE }}" >> apps/desktop/.env
run: echo "{\"analytics_key\":\"${{ secrets.ANALYTICS_BE_WRITE_KEY_PROD }}\",\"analytics_data_plane\":\"${{ secrets.ANALYTICS_DATA_PLANE }}\",\"sentry_dsn_fe\":\"${{ secrets.SENTRY_DSN_FE }}\",\"analytics_key_fe\":\"${{ secrets.ANALYTICS_FE_WRITE_KEY_PROD }}\",\"github_client_id\":\"${{ secrets.APP_GITHUB_CLIENT_ID }}\",\"answer_api_url\":\"${{ secrets.ANSWER_API_URL }}\"}" > apps/desktop/src-tauri/config.json

- name: Check environment is set
run: du -h apps/desktop/src-tauri/config.json

- name: Set providerShortName in tauri.conf.json
uses: jossef/action-set-json-field@v2
Expand Down Expand Up @@ -131,6 +134,6 @@ jobs:
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.name }}-app
name: ${{ matrix.target }}-app
path: target/${{ matrix.target }}/release/bundle
retention-days: 5
5 changes: 0 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
FROM node AS frontend

# set frontend build args
ARG ANALYTICS_FE_WRITE_KEY_PROD
ARG ANALYTICS_DATA_PLANE_URL
ARG SENTRY_DSN_FE

WORKDIR /build
COPY package.json package-lock.json ./
RUN npm ci
Expand Down
30 changes: 1 addition & 29 deletions apps/desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,12 @@
mod backend;
mod qdrant;

use std::{
path::PathBuf,
sync::{Arc, RwLock},
};
use std::{path::PathBuf, sync::RwLock};

use bleep::Application;
use once_cell::sync::OnceCell;
use sentry::ClientInitGuard;
pub use tauri::{plugin, App, Manager, Runtime};

pub static TELEMETRY: RwLock<bool> = RwLock::new(false);
static SENTRY: OnceCell<ClientInitGuard> = OnceCell::new();

// the payload type must implement `Serialize` and `Clone`.
#[derive(Clone, serde::Serialize)]
Expand Down Expand Up @@ -51,33 +45,11 @@ async fn main() {
get_device_id,
enable_telemetry,
disable_telemetry,
initialize_sentry,
])
.run(tauri::generate_context!())
.expect("error running tauri application");
}

#[tauri::command]
fn initialize_sentry(dsn: String, environment: String) {
if sentry::Hub::current().client().is_some() {
tracing::info!("Sentry has already been initialized");
return;
}
let guard = sentry::init((
dsn,
sentry::ClientOptions {
release: sentry::release_name!(),
environment: Some(environment.into()),
before_send: Some(Arc::new(|event| match *TELEMETRY.read().unwrap() {
true => Some(event),
false => None,
})),
..Default::default()
},
));
_ = SENTRY.set(guard);
}

#[tauri::command]
fn enable_telemetry() {
let mut guard = TELEMETRY.write().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
"$schema": "../../../node_modules/@tauri-apps/cli/schema.json",
"build": {
"beforeBuildCommand": "npm run build",
"beforeDevCommand": "npm run dev",
Expand Down
7 changes: 1 addition & 6 deletions apps/desktop/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,6 @@ function App() {
// 1000 * 60 * 60,
// );
});
if (import.meta.env.SENTRY_DSN_BE) {
invoke('initialize_sentry', {
dsn: import.meta.env.SENTRY_DSN_BE,
environment: import.meta.env.MODE,
});
}
}, []);

const deviceContextValue = useMemo(
Expand All @@ -136,6 +130,7 @@ function App() {
isRepoManagementAllowed: true,
forceAnalytics: false,
isSelfServe: false,
envConfig: {},
showNativeMessage: message,
}),
[homeDirectory, indexFolder, deviceId, os, release],
Expand Down
16 changes: 13 additions & 3 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { useCallback, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { DeviceContextType } from './context/deviceContext';
import './index.css';
import './circleProgress.css';
import Tab from './Tab';
import { TabsContext } from './context/tabsContext';
import { UITabType } from './types/general';
import { getJsonFromStorage, SEARCH_HISTORY_KEY } from './services/storage';
import { initApi } from './services/api';
import { getConfig, initApi } from './services/api';
import { useComponentWillMount } from './hooks/useComponentWillMount';
import useKeyboardNavigation from './hooks/useKeyboardNavigation';
import { generateUniqueId } from './utils';
Expand All @@ -17,6 +17,16 @@ type Props = {

function App({ deviceContextValue }: Props) {
useComponentWillMount(() => initApi(deviceContextValue.apiUrl));
const [envConfig, setEnvConfig] = useState({});

useEffect(() => {
getConfig().then(setEnvConfig);
}, []);

const deviceContextWithEnv = useMemo(
() => ({ ...deviceContextValue, envConfig }),
[envConfig],
);

const [tabs, setTabs] = useState<UITabType[]>([
{
Expand Down Expand Up @@ -88,7 +98,7 @@ function App({ deviceContextValue }: Props) {
{tabs.map((t) => (
<Tab
key={t.key}
deviceContextValue={deviceContextValue}
deviceContextValue={deviceContextWithEnv}
isActive={t.key === activeTab}
tab={t}
/>
Expand Down
1 change: 1 addition & 0 deletions client/src/Tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ function Tab({ deviceContextValue, isActive, tab }: Props) {
<AnalyticsContextProvider
deviceId={deviceContextValue.deviceId}
forceAnalytics={deviceContextValue.forceAnalytics}
envConfig={deviceContextValue.envConfig}
>
<DeviceContextProvider deviceContextValue={deviceContextValue}>
<UIContextProvider>
Expand Down
6 changes: 6 additions & 0 deletions client/src/context/deviceContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ export type DeviceContextType = {
isRepoManagementAllowed: boolean;
forceAnalytics: boolean;
isSelfServe: boolean;
envConfig: {
analytics_data_plane?: string;
analytics_key_fe?: string;
sentry_dsn_fe?: string;
};
showNativeMessage: (m: string, options?: any) => Promise<void> | void;
};

Expand All @@ -48,5 +53,6 @@ export const DeviceContext = createContext<DeviceContextType>({
isRepoManagementAllowed: true,
forceAnalytics: false,
isSelfServe: false,
envConfig: {},
showNativeMessage: () => Promise.resolve(),
});
29 changes: 19 additions & 10 deletions client/src/context/providers/AnalyticsContextProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,41 @@ interface AnalyticsProviderProps {
children: React.ReactNode;
deviceId?: string;
forceAnalytics?: boolean;
envConfig: {
analytics_data_plane?: string;
analytics_key_fe?: string;
};
}

export const AnalyticsContextProvider: React.FC<AnalyticsProviderProps> = ({
children,
deviceId,
forceAnalytics,
envConfig,
}) => {
const WRITE_KEY = import.meta.env.PROD
? import.meta.env.ANALYTICS_FE_WRITE_KEY_PROD
: import.meta.env.ANALYTICS_FE_WRITE_KEY_DEV;

const [analyticsLoaded, setAnalyticsLoaded] = useState(false);

const [isAnalyticsAllowed, setIsAnalyticsAllowed] = useState(
forceAnalytics || getPlainFromStorage(IS_ANALYTICS_ALLOWED_KEY) === 'true',
);

const loadAnalytics = async () => {
if (!WRITE_KEY || analyticsLoaded) {
if (
!envConfig.analytics_key_fe ||
!envConfig.analytics_data_plane ||
analyticsLoaded
) {
return;
}

analytics.load(WRITE_KEY, import.meta.env.ANALYTICS_DATA_PLANE_URL, {
logLevel: 'DEBUG',
integrations: { All: true },
});
analytics.load(
envConfig.analytics_key_fe!,
envConfig.analytics_data_plane!,
{
logLevel: 'DEBUG',
integrations: { All: true },
},
);

analytics.ready(() => {
setAnalyticsLoaded(true);
Expand All @@ -55,7 +64,7 @@ export const AnalyticsContextProvider: React.FC<AnalyticsProviderProps> = ({
} else {
setAnalyticsLoaded(false);
}
}, [WRITE_KEY, isAnalyticsAllowed]);
}, [envConfig.analytics_key_fe, isAnalyticsAllowed]);

const analyticsContextValue = useMemo(
() => ({ setIsAnalyticsAllowed, isAnalyticsAllowed, analyticsLoaded }),
Expand Down
10 changes: 7 additions & 3 deletions client/src/context/providers/DeviceContextProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export const DeviceContextProvider = ({
deviceContextValue.invokeTauriCommand(
isAnalyticsAllowed ? 'enable_telemetry' : 'disable_telemetry',
);
if (isAnalyticsAllowed && import.meta.env.SENTRY_DSN_FE) {
if (isAnalyticsAllowed && deviceContextValue.envConfig.sentry_dsn_fe) {
initializeSentry(
import.meta.env.SENTRY_DSN_FE,
deviceContextValue.envConfig.sentry_dsn_fe,
deviceContextValue.release,
);
} else {
Expand All @@ -29,7 +29,11 @@ export const DeviceContextProvider = ({
client.close();
}
}
}, [isAnalyticsAllowed, deviceContextValue.invokeTauriCommand]);
}, [
isAnalyticsAllowed,
deviceContextValue.invokeTauriCommand,
deviceContextValue.envConfig.sentry_dsn_fe,
]);

return (
<DeviceContext.Provider value={deviceContextValue}>
Expand Down
1 change: 1 addition & 0 deletions client/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
isRepoManagementAllowed: true,
isSelfServe: true,
forceAnalytics: true,
envConfig: {},
showNativeMessage: alert,
}}
/>
Expand Down
2 changes: 2 additions & 0 deletions client/src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,5 @@ export const getDiscordLink = () =>

export const githubWebLogin = () =>
http.get('/auth/login/start').then((r) => r.data);

export const getConfig = () => http.get('/config').then((r) => r.data);
2 changes: 2 additions & 0 deletions helm/bloop/templates/bloop-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ spec:
- --analytics-key={{ .Values.bloop.analyticsKey }}
- --analytics-data-plane={{ .Values.bloop.analyticsDataPlane }}
- --sentry-dsn={{ .Values.bloop.sentryDsn }}
- --sentry-dsn-fe={{ .Values.bloop.sentryDsnFE }}
- --analytics-key-fe={{ .Values.bloop.analyticsKeyFE }}
env:
- name: BLOOP_LOG
value: info
Expand Down
2 changes: 2 additions & 0 deletions helm/bloop/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ bloop:
answerApiUrl: ""
qdrantUrl: ""
analyticsKey: ""
analyticsKeyFE: ""
analyticsDataPlane: ""
sentryDsn: ""
sentryDsnFE: ""

image:
repository: ""
Expand Down
11 changes: 11 additions & 0 deletions server/bleep/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ pub struct Configuration {
/// Key for analytics backend
pub analytics_key: Option<String>,

#[clap(long)]
/// Key for analytics backend for frontend
pub analytics_key_fe: Option<String>,

#[clap(long)]
/// Analytics data plane identifier
pub analytics_data_plane: Option<String>,
Expand All @@ -90,6 +94,10 @@ pub struct Configuration {
/// Sentry Data Source Name
pub sentry_dsn: Option<String>,

#[clap(long)]
/// Sentry Data Source Name for frontend
pub sentry_dsn_fe: Option<String>,

//
// Semantic values
//
Expand Down Expand Up @@ -264,10 +272,13 @@ impl Configuration {
bot_secret: b.bot_secret.or(a.bot_secret),

analytics_key: b.analytics_key.or(a.analytics_key),
analytics_key_fe: b.analytics_key_fe.or(a.analytics_key_fe),

analytics_data_plane: b.analytics_data_plane.or(a.analytics_data_plane),

sentry_dsn: b.sentry_dsn.or(a.sentry_dsn),

sentry_dsn_fe: b.sentry_dsn_fe.or(a.sentry_dsn_fe),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions server/bleep/src/webserver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use utoipa::ToSchema;
mod aaa;
pub mod answer;
mod autocomplete;
mod config;
mod file;
mod github;
mod hoverable;
Expand Down Expand Up @@ -41,6 +42,7 @@ pub async fn start(app: Application) -> anyhow::Result<()> {
let bind = SocketAddr::new(app.config.host.parse()?, app.config.port);

let mut api = Router::new()
.route("/config", get(config::handle))
// querying
.route("/q", get(query::handle))
// autocomplete
Expand Down
Loading

0 comments on commit 280b33b

Please sign in to comment.