Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions cueweb/.env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
NEXT_PUBLIC_OPENCUE_ENDPOINT=http://your-rest-gateway-url.com

# Cuebot Facility switching (CueGUI "Cuebot Facility" menu parity).
# NEXT_PUBLIC_CUEBOT_FACILITIES lists the facilities shown in the header menu
# (comma-separated). Defaults to "local,dev,cloud,external" when unset.
# NEXT_PUBLIC_CUEBOT_FACILITIES=local,dev,cloud,external
#
# Each facility may point at its own REST gateway + JWT secret via paired,
# server-only vars named CUEBOT_<NAME>_REST_GATEWAY_URL and
# CUEBOT_<NAME>_JWT_SECRET (NAME uppercased). A facility with no override falls
# back to NEXT_PUBLIC_OPENCUE_ENDPOINT / NEXT_JWT_SECRET, so the default
# deployment works with only the "local" facility wired up.
# CUEBOT_DEV_REST_GATEWAY_URL=http://dev-rest-gateway:8448
# CUEBOT_DEV_JWT_SECRET=dev-gateway-jwt-secret
# CUEBOT_CLOUD_REST_GATEWAY_URL=https://cloud-rest-gateway.example.com
# CUEBOT_CLOUD_JWT_SECRET=cloud-gateway-jwt-secret

# Sentry values
SENTRY_ENVIRONMENT='development'
SENTRY_DSN = sentrydsn
Expand Down
9 changes: 6 additions & 3 deletions cueweb/app/api/health/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import { NextResponse } from "next/server";

import { createJwtToken } from "@/app/utils/api_utils";
import { getRequestFacilityTarget } from "@/lib/facility";

interface JwtParams {
sub: string;
Expand Down Expand Up @@ -49,7 +50,9 @@ interface HealthBody {
}

export async function GET(): Promise<NextResponse<HealthBody>> {
const gateway = process.env.NEXT_PUBLIC_OPENCUE_ENDPOINT;
// Probe the gateway for the facility selected in the request cookie, so the
// status bar reflects the facility the rest of the app is talking to.
const { gatewayUrl: gateway, jwtSecret } = await getRequestFacilityTarget();
const checkedAt = new Date().toISOString();

if (!gateway) {
Expand All @@ -59,7 +62,7 @@ export async function GET(): Promise<NextResponse<HealthBody>> {
status: 0,
latencyMs: 0,
checkedAt,
error: "NEXT_PUBLIC_OPENCUE_ENDPOINT is not configured",
error: "No REST gateway configured for the selected facility",
},
{ status: 200 },
);
Expand All @@ -74,7 +77,7 @@ export async function GET(): Promise<NextResponse<HealthBody>> {

let token: string;
try {
token = createJwtToken(jwtParams);
token = createJwtToken(jwtParams, jwtSecret);
} catch (err) {
console.error("Health JWT signing failed", err);
return NextResponse.json(
Expand Down
22 changes: 14 additions & 8 deletions cueweb/app/utils/api_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import jwt from "jsonwebtoken";
import { NextResponse } from "next/server";
import { handleError } from "./notify_utils";
import { getRequestFacilityTarget } from "@/lib/facility";

/************************************************************/
// Utility functions for accessing the Api including:
Expand All @@ -39,16 +40,19 @@ export async function fetchObjectFromRestGateway(
method: string,
body: string
): Promise<NextResponse> {
const NEXT_PUBLIC_OPENCUE_ENDPOINT = process.env.NEXT_PUBLIC_OPENCUE_ENDPOINT;
const url = `${NEXT_PUBLIC_OPENCUE_ENDPOINT}${endpoint}`;

// Route to the gateway for the facility selected in the request cookie
// (Cuebot Facility menu). Falls back to the default/legacy gateway when
// no per-facility config is present.
const { gatewayUrl, jwtSecret } = await getRequestFacilityTarget();
const url = `${gatewayUrl}${endpoint}`;

Comment thread
ramonfigueiredo marked this conversation as resolved.
const jwtParams: JwtParams = {
sub: "user-id", // Replace with a user id
role: "user-role", // Replace with the user's role
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 3600, // Expires in 1 hour
};
const jwtToken = createJwtToken(jwtParams);
const jwtToken = createJwtToken(jwtParams, jwtSecret);

try {
const response = await fetch(url, {
Expand All @@ -73,11 +77,13 @@ export async function fetchObjectFromRestGateway(
}
}

// Create the JWT token given the payload parameters
export function createJwtToken({ sub, role, iat, exp }: JwtParams): string {
const NEXT_JWT_SECRET = process.env.NEXT_JWT_SECRET;
// Create the JWT token given the payload parameters. The signing secret
// defaults to NEXT_JWT_SECRET but can be overridden per facility (the target
// gateway trusts its own secret).
export function createJwtToken({ sub, role, iat, exp }: JwtParams, secret?: string): string {
const signingSecret = secret ?? process.env.NEXT_JWT_SECRET;
const payload = { sub, role, iat, exp };
return jwt.sign(payload, NEXT_JWT_SECRET as string);
return jwt.sign(payload, signingSecret as string);
Comment thread
ramonfigueiredo marked this conversation as resolved.
Outdated
}


Expand Down
40 changes: 37 additions & 3 deletions cueweb/app/utils/use_cuebot_facility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,39 @@ import * as React from "react";
* across components via a CustomEvent (same tab) + the browser `storage`
* event (cross-tab).
*
* NOTE: this hook persists and broadcasts the selection. Actually routing
* REST-gateway calls per-facility is a separate task. Until that lands, the value is informational.
* The selection is ALSO written to a cookie (`cueweb.facility`) so server-side
* API routes can resolve the per-facility REST gateway for each request (see
* `lib/facility.ts`). Selecting a facility reloads the page so every view
* re-fetches against the newly selected gateway — mirroring CueGUI, which
* clears and re-fetches all data on a facility switch.
*/

export const STORAGE_KEY = "cueweb.facility.selected";
const CHANGE_EVENT = "cueweb:facility-changed";
// Cookie read server-side by lib/facility.ts (FACILITY_COOKIE). Keep in sync.
const COOKIE_KEY = "cueweb.facility";

const DEFAULT_FACILITIES = ["local", "dev", "cloud", "external"] as const;

/** Mirror the selection into a cookie the server reads on every request. */
function writeCookie(value: string): void {
if (typeof document === "undefined") return;
// Not HttpOnly: the client sets it for instant routing, and the server
// re-validates the value against the configured facility list, so a tampered
// cookie can only ever select another already-configured facility.
const oneYear = 60 * 60 * 24 * 365;
document.cookie = `${COOKIE_KEY}=${encodeURIComponent(value)}; path=/; max-age=${oneYear}; samesite=lax`;
}

/** Read the facility cookie (returns null when absent). */
function readCookie(): string | null {
if (typeof document === "undefined") return null;
const row = document.cookie
.split("; ")
.find((r) => r.startsWith(`${COOKIE_KEY}=`));
return row ? decodeURIComponent(row.slice(COOKIE_KEY.length + 1)) : null;
Comment thread
ramonfigueiredo marked this conversation as resolved.
Outdated
}

/** Parse the build-time env var; falls back to the CueGUI defaults. */
function readFacilitiesFromEnv(): string[] {
const raw = process.env.NEXT_PUBLIC_CUEBOT_FACILITIES ?? "";
Expand Down Expand Up @@ -84,7 +108,11 @@ export function useCuebotFacility(): {
);

React.useEffect(() => {
setFacilityState(readSelected(facilities));
const current = readSelected(facilities);
setFacilityState(current);
// Propagate a pre-existing localStorage selection (set before the cookie
// existed) to the cookie so server routes pick it up without a reselect.
if (readCookie() !== current) writeCookie(current);

const customHandler = () => setFacilityState(readSelected(facilities));
const storageHandler = (e: StorageEvent) => {
Expand All @@ -102,10 +130,16 @@ export function useCuebotFacility(): {
const setFacility = React.useCallback(
(next: string) => {
if (!facilities.includes(next)) return;
const previous = readSelected(facilities);
writeSelected(next);
writeCookie(next);
setFacilityState(next);
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
// Re-fetch everything against the newly selected gateway. CueGUI clears
// and reloads all data on a facility switch; a full reload is the
// simplest equivalent and guarantees no stale cross-facility data.
if (next !== previous) window.location.reload();
}
},
[facilities],
Expand Down
16 changes: 15 additions & 1 deletion cueweb/components/ui/status-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

import { usePathname } from "next/navigation";
import * as React from "react";
import { Activity, Clock, Tag } from "lucide-react";
import { Activity, Clock, Server, Tag } from "lucide-react";

import { cn } from "@/lib/utils";
import { useCuebotFacility } from "@/app/utils/use_cuebot_facility";

/**
* IDE-style fixed status bar mounted at the bottom of every authenticated
Expand Down Expand Up @@ -92,6 +93,7 @@ function StatusItem({

export function StatusBar() {
const pathname = usePathname();
const { facility } = useCuebotFacility();
const [health, setHealth] = React.useState<HealthBody | null>(null);
const [lastRefresh, setLastRefresh] = React.useState<string | null>(null);
// Tick once per second so relative timestamps stay fresh without waiting
Expand Down Expand Up @@ -221,6 +223,18 @@ export function StatusBar() {

<span className="mx-1 h-3 w-px bg-border dark:bg-zinc-700" aria-hidden="true" />

<StatusItem
icon={Server}
title={`Active Cuebot facility: ${facility}`}
label={
<>
Facility: <span className="font-medium uppercase">{facility}</span>
</>
}
/>

<span className="mx-1 h-3 w-px bg-border dark:bg-zinc-700" aria-hidden="true" />

<StatusItem
icon={Clock}
title={refreshTitle}
Expand Down
120 changes: 120 additions & 0 deletions cueweb/lib/facility.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright Contributors to the OpenCue Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* Server-side Cuebot facility resolver (CueGUI "Cuebot Facility" parity).
*
* CueGUI maps a facility name to a list of Cuebot host:port pairs
* (`cuebot.facility` in opencue's config) and rewires the gRPC connection
* when the user switches (`Cuebot.setHostWithFacility`). CueWeb talks to the
* REST gateway rather than gRPC directly, so the CueWeb analog maps a facility
* name to a REST-gateway base URL + the JWT secret that gateway trusts.
*
* The selected facility travels from the browser to the server in a cookie
* (see `FACILITY_COOKIE`); every gateway-bound API route resolves the target
* for the current request via `getRequestFacilityTarget()`.
*
* Configuration (all server-side, optional):
* NEXT_PUBLIC_CUEBOT_FACILITIES comma-separated facility names (the menu).
* CUEBOT_<NAME>_REST_GATEWAY_URL gateway base URL for that facility.
* CUEBOT_<NAME>_JWT_SECRET JWT secret for that facility's gateway.
*
* When a facility has no explicit *_REST_GATEWAY_URL / *_JWT_SECRET, it falls
* back to the legacy single-gateway vars (NEXT_PUBLIC_OPENCUE_ENDPOINT /
* NEXT_JWT_SECRET), so the default deployment keeps working with zero new
* config and only the `local` facility wired up.
*
* NOTE: `getRequestFacilityTarget()` reads `next/headers` and only runs
* server-side. It uses a *dynamic* import so this module stays free of a
* static `next/headers` dependency — `api_utils.ts` (which imports this
* module) is also part of the client bundle, and Next.js forbids a static
* `next/headers` import anywhere in the client graph. The pure helpers below
* are safe to import from anywhere. Client components that need the cookie
* name use the literal in `use_cuebot_facility.ts`, kept in sync with
* `FACILITY_COOKIE`.
*/

/** Cookie carrying the selected facility name. Mirrors the localStorage value
* written by `useCuebotFacility`; must match the literal there. */
export const FACILITY_COOKIE = "cueweb.facility";

/** Default facility list — matches CueGUI's example `cuebot.facility` keys. */
const DEFAULT_FACILITIES = ["local", "dev", "cloud", "external"] as const;

export interface FacilityTarget {
/** The resolved (validated) facility name. */
name: string;
/** REST gateway base URL to send this request to. */
gatewayUrl: string;
/** JWT secret the target gateway trusts. */
jwtSecret: string;
}

/** The configured facility names (the menu). Falls back to the CueGUI defaults. */
export function getConfiguredFacilities(): string[] {
const raw = process.env.NEXT_PUBLIC_CUEBOT_FACILITIES ?? "";
const parsed = raw
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0);
return parsed.length > 0 ? parsed : [...DEFAULT_FACILITIES];
}

/** "dev" -> "CUEBOT_DEV_REST_GATEWAY_URL". Non-alphanumerics become "_". */
function envKey(facility: string, suffix: string): string {
const norm = facility.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
return `CUEBOT_${norm}_${suffix}`;
}

/**
* Resolve a facility name to its gateway target. Unknown / unconfigured names
* fall back to the first configured facility (the default), mirroring CueGUI's
* `setHostWithFacility` which falls back to `cuebot.facility_default`.
*/
export function resolveFacilityTarget(name: string | undefined): FacilityTarget {
const facilities = getConfiguredFacilities();
const fallbackName = facilities[0] ?? "local";
const facility = name && facilities.includes(name) ? name : fallbackName;

const gatewayUrl =
process.env[envKey(facility, "REST_GATEWAY_URL")] ??
process.env.NEXT_PUBLIC_OPENCUE_ENDPOINT ??
"";
const jwtSecret =
process.env[envKey(facility, "JWT_SECRET")] ??
process.env.NEXT_JWT_SECRET ??
"";

return { name: facility, gatewayUrl, jwtSecret };
}

/**
* Resolve the facility target for the current request, reading the selection
* from the request cookie and validating it against the configured list.
* Safe to call outside a request scope (returns the default target).
*/
export async function getRequestFacilityTarget(): Promise<FacilityTarget> {
let selected: string | undefined;
try {
// Dynamic import keeps next/headers out of the static client graph.
const { cookies } = await import("next/headers");
const store = await cookies();
selected = store.get(FACILITY_COOKIE)?.value;
} catch {
// Not in a request scope (e.g. build-time): use the default.
}
return resolveFacilityTarget(selected);
}
9 changes: 9 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,15 @@ services:
environment:
# Runtime environment variables
- NEXT_PUBLIC_OPENCUE_ENDPOINT=http://rest-gateway:8448
# Cuebot Facility switching (CueGUI "Cuebot Facility" menu parity).
# NEXT_PUBLIC_CUEBOT_FACILITIES lists the facilities in the header menu;
# defaults to "local,dev,cloud,external". Each facility can target its own
# gateway via CUEBOT_<NAME>_REST_GATEWAY_URL + CUEBOT_<NAME>_JWT_SECRET
# (server-only); a facility without overrides falls back to
# NEXT_PUBLIC_OPENCUE_ENDPOINT / NEXT_JWT_SECRET below. Examples:
# - NEXT_PUBLIC_CUEBOT_FACILITIES=local,dev,cloud,external
# - CUEBOT_DEV_REST_GATEWAY_URL=http://dev-rest-gateway:8448
# - CUEBOT_DEV_JWT_SECRET=${JWT_SECRET:-opencue-dev-jwt-secret-change-in-production}
# See the build args block above - empty means same-origin relative.
- NEXT_PUBLIC_URL=
# See the build args block above. Runtime value is only useful if
Expand Down
12 changes: 12 additions & 0 deletions docs/_docs/developer-guide/cueweb-development.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ cueweb/
│ └── context_menus/ # Right-click context menus (Job / Layer / Frame)
├── lib/ # Utility libraries
│ ├── auth.ts # NextAuth configuration (Okta/Google/GitHub/LDAP)
│ ├── facility.ts # Cuebot Facility resolver (per-request gateway + JWT)
│ ├── utils.ts # General utilities (incl. cn())
│ └── metrics-service.ts # Prometheus metrics
├── public/ # Static assets
Expand Down Expand Up @@ -221,6 +222,17 @@ provider tree.
- Key: `cueweb.facility.selected`. Event: `cueweb:facility-changed`.
- Available facilities are read from `NEXT_PUBLIC_CUEBOT_FACILITIES`
(comma-separated); defaults to `local,dev,cloud,external`.
- `setFacility` also mirrors the selection into the `cueweb.facility` cookie
(so server routes can read it) and reloads the page so every view re-fetches
against the newly selected gateway &mdash; mirroring CueGUI, which clears and
re-fetches all data on a facility change.
- Server-side routing lives in `lib/facility.ts`. `getRequestFacilityTarget()`
reads the cookie and resolves the facility to a REST gateway URL + JWT secret
from `CUEBOT_<NAME>_REST_GATEWAY_URL` / `CUEBOT_<NAME>_JWT_SECRET`, falling
back to `NEXT_PUBLIC_OPENCUE_ENDPOINT` / `NEXT_JWT_SECRET`. Every proxied
request goes through it via `fetchObjectFromRestGateway` (`app/utils/api_utils.ts`),
and `/api/health` probes the selected facility's gateway. (`next/headers` is
imported dynamically there so the module stays out of the client bundle.)
- **`useAttributesPanel`** (`app/utils/use_attributes_panel.ts`)
&mdash; `{ isOpen, position, positions, setOpen, toggle, setPosition }`.
- Keys: `cueweb.attributes.open` (`bool`) and `cueweb.attributes.position`
Expand Down
Loading
Loading