Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
30 changes: 15 additions & 15 deletions SW.Bitween.Api/Services/RunFlagUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,21 @@ public async Task<bool> MarkAsRunning(int id)
{
var sqlUpdate = _dbType.ToLower() switch
{
"pgsql" => $@"UPDATE infolink.subscription SET is_running = true
WHERE id = '{id}' and is_running = false
"pgsql" => @"UPDATE infolink.subscription SET is_running = true
WHERE id = {0} and is_running = false
RETURNING is_running",
"mssql" => $@"UPDATE Subscriptions SET IsRunning = 1
"mssql" => @"UPDATE Subscriptions SET IsRunning = 1
OUTPUT INSERTED.IsRunning
WHERE Id = '{id}' and IsRunning = 0",
"mysql" => $@"SELECT IsRunning FROM Subscriptions
WHERE Id = '{id}' and IsRunning = false
WHERE Id = {0} and IsRunning = 0",
"mysql" => @"SELECT IsRunning FROM Subscriptions
WHERE Id = {0} and IsRunning = false
FOR UPDATE;
UPDATE Subscriptions SET IsRunning = true
WHERE Id = '{id}' and IsRunning = false",
WHERE Id = {0} and IsRunning = false",
_ => ""
};

var results = await dbContext.Set<RunningResult>().FromSqlRaw(sqlUpdate).ToListAsync();
var results = await dbContext.Set<RunningResult>().FromSqlRaw(sqlUpdate, id).ToListAsync();

var result = results.SingleOrDefault();
// result is null when is running is true
Expand All @@ -46,17 +46,17 @@ public async Task MarkAsIdle(int id)
{
var sqlUpdate = _dbType.ToLower() switch
{
"pgsql" => $@"UPDATE infolink.subscription SET is_running = false
WHERE id = '{id}'",
"mssql" => $@"UPDATE Subscriptions SET IsRunning = 0
WHERE Id = '{id}'",
"mysql" => $@"UPDATE Subscriptions SET IsRunning = false
WHERE Id = '{id}'",
"pgsql" => @"UPDATE infolink.subscription SET is_running = false
WHERE id = {0}",
"mssql" => @"UPDATE Subscriptions SET IsRunning = 0
WHERE Id = {0}",
"mysql" => @"UPDATE Subscriptions SET IsRunning = false
WHERE Id = {0}",
_ => ""
};
;

await dbContext.Database.ExecuteSqlRawAsync(sqlUpdate);
await dbContext.Database.ExecuteSqlRawAsync(sqlUpdate, id);
}

public class RunningResult
Expand Down
72 changes: 72 additions & 0 deletions SW.Bitween.IntegrationTests/Tests/RunFlagUpdaterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SW.Bitween.Domain;
using SW.Bitween.IntegrationTests.Fixtures;
using SW.Bitween.Model;
using Xunit;

namespace SW.Bitween.IntegrationTests.Tests;

// The run flag is written with raw (parameterized) SQL that differs per database
// provider, so it needs a real round trip to prove the statement and its parameter
// binding are correct. There was no coverage here before.
[Collection("Bitween")]
public class RunFlagUpdaterTests
{
private readonly BitweenFixture _fixture;

public RunFlagUpdaterTests(BitweenFixture fixture)
{
_fixture = fixture;
}

[Fact]
public async Task Run_flag_claims_once_then_blocks_until_idle()
{
await using var scope = _fixture.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<BitweenDbContext>();
var runFlag = scope.ServiceProvider.GetRequiredService<RunFlagUpdater>();

var document = new Document(6101, "Run Flag Test Doc");
db.Set<Document>().Add(document);
var subscription = new Subscription("Run Flag Test", document.Id);
subscription.Inactive = false;
db.Set<Subscription>().Add(subscription);
await db.SaveChangesAsync();

Assert.True(await runFlag.MarkAsRunning(subscription.Id)); // first claim wins
Assert.False(await runFlag.MarkAsRunning(subscription.Id)); // already running

await runFlag.MarkAsIdle(subscription.Id);

Assert.True(await runFlag.MarkAsRunning(subscription.Id)); // claimable again
await runFlag.MarkAsIdle(subscription.Id);
}

// Guards the parameter binding: a broken placeholder would either match no rows
// or every row, and both would show up here.
[Fact]
public async Task Run_flag_only_affects_the_requested_subscription()
{
await using var scope = _fixture.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<BitweenDbContext>();
var runFlag = scope.ServiceProvider.GetRequiredService<RunFlagUpdater>();

var document = new Document(6102, "Run Flag Isolation Doc");
db.Set<Document>().Add(document);
var a = new Subscription("Run Flag A", document.Id);
a.Inactive = false;
var b = new Subscription("Run Flag B", document.Id);
b.Inactive = false;
db.Set<Subscription>().AddRange(a, b);
await db.SaveChangesAsync();

Assert.True(await runFlag.MarkAsRunning(a.Id));
Assert.True(await runFlag.MarkAsRunning(b.Id)); // b untouched by a's update

await runFlag.MarkAsIdle(a.Id);
Assert.False(await runFlag.MarkAsRunning(b.Id)); // b still running, a's idle did not clear it

await runFlag.MarkAsIdle(b.Id);
}
}
8 changes: 6 additions & 2 deletions SW.Bitween.Web/ClientApp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@
},
"dependencies": {
"@azure/msal-browser": "^4.0.1",
"@babel/runtime": "^8.0.0",
"@codemirror/language": "^6.12.4",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
"@codemirror/state": "^6.7.2",
"@codemirror/view": "^6.43.10",
"@fontsource-variable/instrument-sans": "^5.2.8",
"@fontsource-variable/jetbrains-mono": "^5.2.8",
"@headlessui/react": "^2.2.10",
"@monaco-editor/loader": "^1.7.0",
"@monaco-editor/react": "^4.7.0",
"@lezer/highlight": "^1.2.3",
"@tailwindcss/vite": "^4.3.2",
"@tanstack/react-query": "^5.101.2",
"@uiw/react-codemirror": "^4.25.11",
"immer": "^11.1.8",
"lucide-react": "^1.24.0",
"react": "^19.2.7",
Expand Down
5 changes: 5 additions & 0 deletions SW.Bitween.Web/ClientApp/src/auth/SessionContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from "react";
import { useQueryClient } from "@tanstack/react-query";
import { api, type PermissionKey, type Session } from "../api";
import { useIdleLogout } from "./useIdleLogout";

interface SessionContextValue {
session: Session | null;
Expand Down Expand Up @@ -72,6 +73,10 @@ export function SessionProvider({ children }: { children: ReactNode }) {
setSession(null);
}, [queryClient]);

// Finding #4 in the 9USRCraft pen test: an authenticated session stayed usable
// indefinitely. Signs out after 30 minutes with no activity in any tab.
useIdleLogout(!!session, signOut);

const value = useMemo<SessionContextValue>(
() => ({
session,
Expand Down
91 changes: 91 additions & 0 deletions SW.Bitween.Web/ClientApp/src/auth/useIdleLogout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { useEffect, useRef } from "react";

const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
const CHECK_INTERVAL_MS = 30 * 1000; // re-check every 30s
const ACTIVITY_EVENTS = ["mousemove", "mousedown", "keydown", "scroll", "touchstart"];
/** Shared so activity in any tab keeps every tab alive (see the interval below). */
const LAST_ACTIVITY_KEY = "last_activity";

const readSharedActivity = (): number => {
try {
return Number(localStorage.getItem(LAST_ACTIVITY_KEY)) || 0;
} catch {
return 0; // storage unavailable: fall back to this tab's own timer
}
};

const writeSharedActivity = (ts: number) => {
try {
localStorage.setItem(LAST_ACTIVITY_KEY, String(ts));
} catch {
// ignore: the in-tab ref still tracks activity
}
};

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/**
* Signs the user out after a period with no activity in any tab. Runs the normal
* sign-out path, so an idle session ends exactly like clicking Sign out.
*/
export function useIdleLogout(
enabled: boolean,
signOut: () => Promise<void>,
timeoutMs: number = IDLE_TIMEOUT_MS,
) {
const lastActivity = useRef<number>(Date.now());
// Held in a ref so a new signOut identity doesn't restart the idle timer.
const signOutRef = useRef(signOut);
useEffect(() => {
signOutRef.current = signOut;
}, [signOut]);

useEffect(() => {
if (!enabled) return;

// Start counting from the moment we become enabled. The ref is created when the
// provider first mounts, which is while the login page is showing and no activity
// listeners are attached, so without this a login page left open longer than
// timeoutMs would sign the user out immediately after signing in.
const enabledAt = Date.now();
lastActivity.current = enabledAt;
writeSharedActivity(enabledAt);

const markActivity = () => {
const ts = Date.now();
lastActivity.current = ts;
writeSharedActivity(ts);
};
ACTIVITY_EVENTS.forEach((e) => window.addEventListener(e, markActivity, { passive: true }));

const interval = window.setInterval(async () => {
// Activity events only fire in the focused tab, so take the most recent activity
// across tabs. Otherwise a background tab would sign out a user who is actively
// working in another one.
const last = Math.max(lastActivity.current, readSharedActivity());
if (Date.now() - last < timeoutMs) return;

window.clearInterval(interval);
ACTIVITY_EVENTS.forEach((e) => window.removeEventListener(e, markActivity));
try {
await signOutRef.current();
} catch {
// Only the server call invalidates the refresh-token cookie (it is HttpOnly,
// so JS cannot clear it). Retry once before giving up.
await sleep(2000);
try {
await signOutRef.current();
} catch {
// api.logout() clears the stored Jwt in a finally, so it is already gone by
// now; reloading is what drops the in-memory session and shows the login page.
window.location.reload();
}
}
}, CHECK_INTERVAL_MS);

return () => {
window.clearInterval(interval);
ACTIVITY_EVENTS.forEach((e) => window.removeEventListener(e, markActivity));
};
}, [enabled, timeoutMs]);
}
83 changes: 39 additions & 44 deletions SW.Bitween.Web/ClientApp/src/components/mapper/ManualEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React, { lazy, Suspense, useEffect, useRef } from "react";
import loader from "@monaco-editor/loader";
import React, { useEffect } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { EditorView } from "@codemirror/view";
import { scribanLanguage } from "./scribanLanguage";
import {
useMappingEditorDispatch,
useMappingEditorState,
Expand All @@ -10,21 +12,19 @@ import {
} from "../../lib/mapping/MappingEditorContext";
import { generateScriban, parseScriban } from "../../lib/mapping/scribanGenerator";

// Pinned to an exact version so the CSP entries in Startup.cs (which allow only
// this path, not all of cdn.jsdelivr.net) stay valid — bump both together.
loader.config({ paths: { vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs" } });

// Monaco is heavy — lazy-load it so it stays out of the main bundle.
const MonacoEditor = lazy(() => import("@monaco-editor/react"));

const SCRIBAN_HINT = `{{- # Scriban template — edit freely -}}
{{- # Use {{ variable.path }} for values, for/end for loops, if/end for filters -}}
`;

const editorTheme = EditorView.theme({
'&': { height: '100%', backgroundColor: '#ffffff' },
'.cm-scroller': { fontFamily: 'var(--font-mono)', overflow: 'auto' },
'&.cm-focused': { outline: 'none' },
});

const ManualEditor: React.FC = () => {
const dispatch = useMappingEditorDispatch();
const { fieldMappings, arrayMappings, manualTemplate, isManualDirty } = useMappingEditorState();
const editorRef = useRef<any>(null);
const [parseWarnings, setParseWarnings] = React.useState<string[]>([]);
const [parseSuccess, setParseSuccess] = React.useState(false);

Expand All @@ -39,14 +39,15 @@ const ManualEditor: React.FC = () => {
}
}, []); // Only on mount — ongoing sync is handled by handleModeChange

const handleEditorChange = (value: string | undefined) => {
dispatch(setManualTemplate(value ?? ''));
const handleEditorChange = (value: string) => {
dispatch(setManualTemplate(value));
};

const handleRegenerateFromVisual = () => {
const generated = generateScriban(fieldMappings, arrayMappings, undefined, undefined);
// syncManualTemplate updates manualTemplate, which flows into the editor's
// controlled `value` below — no imperative setValue needed.
dispatch(syncManualTemplate(generated));
editorRef.current?.setValue(generated);
setParseWarnings([]);
setParseSuccess(false);
};
Expand Down Expand Up @@ -77,11 +78,15 @@ const ManualEditor: React.FC = () => {
}
};

const templateToShow =
manualTemplate ||
(fieldMappings.length > 0 || arrayMappings.length > 0
? generateScriban(fieldMappings, arrayMappings, undefined, undefined)
: SCRIBAN_HINT);
// Once the user has edited the template (isManualDirty), show it verbatim so an
// intentional empty template stays empty. Only before any edit do we fall back to
// the generated template / hint.
const templateToShow = isManualDirty
? manualTemplate
: manualTemplate ||
(fieldMappings.length > 0 || arrayMappings.length > 0
? generateScriban(fieldMappings, arrayMappings, undefined, undefined)
: SCRIBAN_HINT);

return (
<div className="flex flex-col h-full">
Expand Down Expand Up @@ -130,31 +135,21 @@ const ManualEditor: React.FC = () => {
</div>
)}

{/* Monaco Editor */}
{/* CodeMirror editor */}
<div className="flex-1 min-h-0">
<Suspense fallback={<div className="flex h-full items-center justify-center text-sm text-ink-400">Loading editor…</div>}>
<MonacoEditor
language="handlebars"
theme="vs"
value={templateToShow}
onChange={handleEditorChange}
onMount={(ed) => {
editorRef.current = ed;
}}
options={{
minimap: { enabled: true },
fontSize: 13,
lineNumbers: 'on',
wordWrap: 'on',
scrollBeyondLastLine: false,
fontFamily: '"Fira Code", "JetBrains Mono", monospace',
automaticLayout: true,
formatOnPaste: true,
tabSize: 2,
suggest: { snippetsPreventQuickSuggestions: false },
}}
/>
</Suspense>
<CodeMirror
value={templateToShow}
onChange={handleEditorChange}
extensions={[scribanLanguage, EditorView.lineWrapping, editorTheme]}
height="100%"
basicSetup={{
lineNumbers: true,
foldGutter: false,
autocompletion: false,
highlightActiveLine: true,
}}
className="h-full text-[13px]"
/>
</div>

{/* Scriban cheat sheet */}
Expand All @@ -164,8 +159,8 @@ const ManualEditor: React.FC = () => {
<span className="text-crimson-600">{'{{ var.path }}'}</span> value
</span>
<span>
<span className="text-crimson-600">{'{{- for item in arr -}}'}</span> …{' '}
<span className="text-crimson-600">{'{{- end -}}'}</span> loop
<span className="text-warn-700">{'{{- for item in arr -}}'}</span> …{' '}
<span className="text-warn-700">{'{{- end -}}'}</span> loop
</span>
<span>
<span className="text-warn-700">{'{{- if expr -}}'}</span> …{' '}
Expand Down
Loading
Loading