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
8 changes: 8 additions & 0 deletions .mcp.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"mcpServers": {
"foldkit-devtools": {
"command": "pnpm",
"args": ["exec", "foldkit-devtools-mcp"]
}
}
}
31 changes: 19 additions & 12 deletions CONTRIBUTING.md

Large diffs are not rendered by default.

42 changes: 12 additions & 30 deletions apps/bot/src/Storage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Cause, Effect, ErrorReporter, Layer, Option } from "effect";
import { Cause, type Context, Effect, ErrorReporter, Layer, Option } from "effect";
import { ConsentRequests } from "recording-requests/ConsentRequests";
import { RecordingEdits } from "recording-requests/RecordingEdits";
import { RecordingRequests } from "recording-requests/RecordingRequests";
Expand Down Expand Up @@ -28,32 +28,14 @@ const disabled = Layer.mergeAll(
ErasureStore.layerDisabled,
);

const recordingRequests = Layer.effect(
RecordingRequests,
Effect.gen(function* () {
const database = yield* Database;

return yield* RecordingRequests.make(database.ready);
}),
);

const recordingEdits = Layer.effect(
RecordingEdits,
Effect.gen(function* () {
const database = yield* Database;

return yield* RecordingEdits.make(database.ready);
}),
);

const consentRequests = Layer.effect(
ConsentRequests,
Effect.gen(function* () {
const database = yield* Database;

return yield* ConsentRequests.make(database.ready);
}),
);
const onceDatabaseReady = <I, S, E, R>(
service: Context.Key<I, S>,
make: (ready: Effect.Effect<void>) => Effect.Effect<S, E, R>,
) =>
Layer.effect(
service,
Effect.flatMap(Effect.service(Database), (database) => make(database.ready)),
);

export const StorageLayer = Layer.unwrap(
Effect.gen(function* () {
Expand All @@ -70,9 +52,9 @@ export const StorageLayer = Layer.unwrap(
OfficeHistory.layer,
SlackHistory.layer,
RecordingStore.layer,
recordingRequests,
recordingEdits,
consentRequests,
onceDatabaseReady(RecordingRequests, RecordingRequests.make),
onceDatabaseReady(RecordingEdits, RecordingEdits.make),
onceDatabaseReady(ConsentRequests, ConsentRequests.make),
ErasureStore.layer,
ConsentBook.layer.pipe(Layer.provide(ConsentLog.layer)),
).pipe(
Expand Down
10 changes: 10 additions & 0 deletions apps/bot/src/activity/ActivityLog.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Context, DateTime, Effect, Layer, pipe, Predicate, Schema, String } from "effect";
import { SqlClient, type SqlError } from "effect/sql";
import { QUERY_TIMEOUT, TIMED_OUT } from "recording-requests/Query";

import { describeError } from "../database/index.ts";
import type { TimedVoiceEffect, VoiceObservation } from "../office/index.ts";
Expand Down Expand Up @@ -27,6 +28,15 @@ export class ActivityLogError extends Schema.TaggedError<
reason: Schema.Union([Outage, BadRow]),
}) {}

export const withinQueryTimeout = <A, R>(query: Effect.Effect<A, ActivityLogError, R>) =>
query.pipe(
Effect.timeoutOrElse({
duration: QUERY_TIMEOUT,
orElse: () =>
Effect.fail(ActivityLogError.make({ reason: Outage.make({ message: TIMED_OUT }) })),
}),
);

// Data exceptions (class 22) and integrity violations (class 23) are about the
// row. Anything else, even unrecognised, is treated as an outage: retrying
// forever is better than setting aside a row that was fine.
Expand Down
15 changes: 3 additions & 12 deletions apps/bot/src/activity/ActivityRecorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ import {
Schema,
} from "effect";
import { SecureRandom } from "effect/crypto";
import { QUERY_TIMEOUT, TIMED_OUT } from "recording-requests/Query";
import { QUERY_TIMEOUT } from "recording-requests/Query";

import { ActivityLog, ActivityLogError, Outage } from "./ActivityLog.ts";
import { ActivityLog, type ActivityLogError, Outage, withinQueryTimeout } from "./ActivityLog.ts";
import {
Database,
DatabaseUnavailable,
Expand Down Expand Up @@ -193,16 +193,7 @@ export class ActivityRecorder extends Context.Service<
);

const write = (entry: Entry) =>
persist(entry).pipe(
Effect.timeoutOrElse({
duration: QUERY_TIMEOUT,
orElse: () =>
Effect.fail(
ActivityLogError.make({
reason: Outage.make({ message: TIMED_OUT }),
}),
),
}),
withinQueryTimeout(persist(entry)).pipe(
Effect.retry(outageRetry),
Effect.catchTag("ActivityLogError", (error) => setAside(entry, error)),
);
Expand Down
1 change: 1 addition & 0 deletions apps/bot/src/activity/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export {
classify,
memberUpsert,
Outage,
withinQueryTimeout,
} from "./ActivityLog.ts";

export { ActivityRecorder, RecordingDisabled } from "./ActivityRecorder.ts";
Expand Down
2 changes: 1 addition & 1 deletion apps/bot/src/announcing/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { banter, banterLog, banterRequest, periodRange } from "./Banter.ts";
export { banter, banterLog, periodRange } from "./Banter.ts";

export { briefFor, HeadlineWriter } from "./HeadlineWriter.ts";

Expand Down
6 changes: 3 additions & 3 deletions apps/bot/src/consent/ConsentBook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
Schema,
} from "effect";

import { type ActivityLogError, Outage } from "../activity/index.ts";
import { type ActivityLogError, Outage, withinQueryTimeout } from "../activity/index.ts";
import { Database, reconnectSchedule } from "../database/index.ts";
import { type ConsentEvent, ConsentLog, type ConsentRecord, NEVER_ASKED } from "./ConsentLog.ts";

Expand Down Expand Up @@ -134,7 +134,7 @@ export class ConsentBook extends Context.Service<

const book = yield* make(
database.ready.pipe(
Effect.andThen(log.history),
Effect.andThen(withinQueryTimeout(log.history)),
Effect.retry(retryOutages),
Effect.catchCause((cause) =>
Effect.logError(
Expand Down Expand Up @@ -162,7 +162,7 @@ export class ConsentBook extends Context.Service<
Effect.flatMap((erased) =>
erased
? Effect.logInfo("Dropped a consent event noted before that person's data was erased")
: log.append(event),
: withinQueryTimeout(log.append(event)),
),
Effect.retry(retryOutages),
Effect.catch((error) =>
Expand Down
4 changes: 2 additions & 2 deletions apps/bot/src/consent/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { ConsentBook, LOOKUP_WAIT, recordAfter } from "./ConsentBook.ts";
export { ConsentBook, LOOKUP_WAIT } from "./ConsentBook.ts";

export { type ConsentEvent, ConsentLog, type ConsentRecord, NEVER_ASKED } from "./ConsentLog.ts";
export { ConsentLog } from "./ConsentLog.ts";

export * as Notice from "./Notice.ts";
44 changes: 3 additions & 41 deletions apps/bot/src/erasure/ErasureStore.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Array, Context, Effect, Layer, pipe, Schema } from "effect";
import { SqlClient, SqlSchema } from "effect/sql";
import { namesOf, slackIdsOf } from "recording-requests/ErasureInventory";
import { guardChange, guardQuery, type QueryGuard } from "recording-requests/Query";
import { FORMER_MEMBER, FORMER_MEMBER_ID } from "office-domain/wire";

Expand Down Expand Up @@ -29,10 +30,6 @@ export interface Erased {
readonly republishing: number;
}

const NameRow = Schema.Struct({ name: Schema.String });

const SlackIdRow = Schema.Struct({ slackUserId: Schema.String });

const PathRow = Schema.Struct({ objectPath: Schema.String });

const RecordingRow = Schema.Struct({ recordingId: Schema.String });
Expand Down Expand Up @@ -114,41 +111,6 @@ export class ErasureStore extends Context.Service<

const atomically = guardChange(guard, sql);

const findNames = SqlSchema.findAll({
Request: Schema.String,
Result: NameRow,
execute: (userId) => sql`
WITH m AS (SELECT * FROM office.members WHERE user_id = ${userId})
SELECT DISTINCT name FROM (
SELECT display_name AS name FROM m
UNION ALL SELECT real_name FROM m
UNION ALL
SELECT display_name FROM office.slack_messages
WHERE member_user_id = ${userId} OR user_id IN (SELECT slack_user_id FROM m)
UNION ALL
SELECT requested_by_name FROM office.recording_requests WHERE requested_by = ${userId}
UNION ALL
SELECT edited_by_name FROM office.recording_edits WHERE edited_by = ${userId}
) names
WHERE name IS NOT NULL
ORDER BY name
`,
});

const findSlackIds = SqlSchema.findAll({
Request: Schema.String,
Result: SlackIdRow,
execute: (userId) => sql`
SELECT DISTINCT slack_user_id FROM (
SELECT slack_user_id FROM office.members WHERE user_id = ${userId}
UNION ALL
SELECT user_id FROM office.slack_messages WHERE member_user_id = ${userId}
) ids
WHERE slack_user_id IS NOT NULL
ORDER BY slack_user_id
`,
});

const findPaths = SqlSchema.findAll({
Request: Schema.String,
Result: PathRow,
Expand Down Expand Up @@ -185,8 +147,8 @@ export class ErasureStore extends Context.Service<
});

const subject = Effect.fn("ErasureStore.subject")(function* (userId: string) {
const names = yield* onceReady(findNames(userId));
const slackIds = yield* onceReady(findSlackIds(userId));
const names = yield* onceReady(namesOf(sql)(userId));
const slackIds = yield* onceReady(slackIdsOf(sql)(userId));
const paths = yield* onceReady(findPaths(userId));

const slackUserIds = Array.map(slackIds, ({ slackUserId }) => slackUserId);
Expand Down
3 changes: 1 addition & 2 deletions apps/bot/src/erasure/Scrub.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Array, Option, Order, pipe, Predicate, Record, type Schema, String } from "effect";
import { FORMER_MEMBER } from "office-domain/wire";
import { MIN_NAME_LENGTH } from "recording-requests/ErasureInventory";

import { escapeSlackText } from "../slack/index.ts";

export const MIN_NAME_LENGTH = 3;

const DISPLAYED_KEYS: ReadonlySet<string> = new Set(["text", "alt_text"]);

export interface Scrubber {
Expand Down
2 changes: 1 addition & 1 deletion apps/bot/src/erasure/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { Eraser, type PrepareError } from "./Eraser.ts";

export { type Erased, ErasureStore } from "./ErasureStore.ts";
export { ErasureStore } from "./ErasureStore.ts";
15 changes: 2 additions & 13 deletions apps/bot/src/office/BotPresence.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,6 @@
import { Filter, Result } from "effect";

import { OfficeEvent, type Occupants } from "./OfficeEvent.ts";
import type { Occupants } from "./OfficeEvent.ts";

export type BotPresence = "InOffice" | "Away";

export const presenceAtStartup = (occupants: Occupants): BotPresence =>
export const presenceOf = (occupants: Occupants): BotPresence =>
occupants.size > 0 ? "InOffice" : "Away";

const presenceAfterEvent = OfficeEvent.$match({
Opened: (): Result.Result<BotPresence, OfficeEvent> => Result.succeed("InOffice"),
Emptied: (): Result.Result<BotPresence, OfficeEvent> => Result.succeed("Away"),
Reminder: (event): Result.Result<BotPresence, OfficeEvent> => Result.fail(event),
Banter: (event): Result.Result<BotPresence, OfficeEvent> => Result.fail(event),
});

export const presenceAfter = Filter.make(presenceAfterEvent);
18 changes: 9 additions & 9 deletions apps/bot/src/office/DiscordGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import {
type PromptDelivery,
} from "./ConsentGate.ts";

import { type BotPresence, presenceAfter, presenceAtStartup } from "./BotPresence.ts";
import { type BotPresence, presenceOf } from "./BotPresence.ts";
import { DiscordConfig } from "../Config.ts";
import type { SeatAdapter } from "./OfficeSeat.ts";
import { type OfficeVoice, officeVoiceIn } from "./OfficeVoice.ts";
Expand Down Expand Up @@ -93,6 +93,7 @@ const stamped = <A extends VoiceStateUpdate | VoiceEffect, E, R>(updates: Stream
interface Followed {
readonly update: TimedVoiceStateUpdate;
readonly events: ReadonlyArray<OfficeEvent>;
readonly presence: BotPresence;
}

const REPLAYED_UPDATES = 1000;
Expand All @@ -106,7 +107,7 @@ const followOffice =
(session, update): readonly [OfficeSession, ReadonlyArray<Followed>] => {
const [next, events] = trackOccupancy(officeChannelId)(session, update);

return [next, [{ update, events }]];
return [next, [{ update, events, presence: presenceOf(next.occupants) }]];
},
),
Stream.broadcast({ capacity: "unbounded", replay: REPLAYED_UPDATES }),
Expand All @@ -116,6 +117,10 @@ const followOffice =
Stream.map(({ events }) => events),
Stream.flattenIterable,
),
botPresence: Stream.make(presenceOf(occupants)).pipe(
Stream.concat(followed.pipe(Stream.map(({ presence }) => presence))),
Stream.changes,
),
})),
);

Expand Down Expand Up @@ -143,11 +148,6 @@ const officeEffects =
<E, R>(effects: Stream.Stream<VoiceEffect, E, R>): Stream.Stream<TimedVoiceEffect, E, R> =>
stamped(effects).pipe(Stream.filterMap(sentInOffice(officeChannelId)));

const botPresence = <E, R>(occupants: Occupants, events: Stream.Stream<OfficeEvent, E, R>) =>
Stream.make(presenceAtStartup(occupants)).pipe(
Stream.concat(events.pipe(Stream.filterMap(presenceAfter))),
);

const detailsOf = (state: VoiceState): VoiceDetails => ({
selfMute: state.selfMute,
selfDeaf: state.selfDeaf,
Expand Down Expand Up @@ -851,7 +851,7 @@ export class DiscordGateway extends Context.Service<
),
botPresence: Option.match(office, {
onNone: () => Stream.empty,
onSome: () => botPresence(occupants, followed.officeEvents),
onSome: () => followed.botPresence,
}),
seat: Option.flatMap(office, (channel) =>
Option.map(voice, (officeVoice): SeatAdapter => ({
Expand Down Expand Up @@ -944,7 +944,7 @@ export class DiscordGateway extends Context.Service<
officeEffects(officeChannelId),
Stream.filterEffect((effect) => gate.isAdmitted(effect.userId)),
),
botPresence: botPresence(seated, followed.officeEvents),
botPresence: followed.botPresence,
seat: Option.some({
join: () =>
moves === undefined
Expand Down
18 changes: 13 additions & 5 deletions apps/bot/src/office/OfficeVoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,17 @@ const reaches = (connection: VoiceConnection, status: VoiceConnectionStatus) =>
Effect.orElseSucceed(() => false),
);

const leavesReady = (connection: VoiceConnection) =>
Effect.raceAll([
reaches(connection, VoiceConnectionStatus.Signalling),
reaches(connection, VoiceConnectionStatus.Connecting),
reaches(connection, VoiceConnectionStatus.Disconnected),
reaches(connection, VoiceConnectionStatus.Destroyed),
]);

const isDisconnected = (connection: VoiceConnection) =>
connection.state.status === VoiceConnectionStatus.Disconnected;

const recovers = (connection: VoiceConnection) =>
Effect.raceFirst(
reaches(connection, VoiceConnectionStatus.Signalling),
Expand Down Expand Up @@ -236,14 +247,11 @@ export const officeVoiceIn = Effect.fnUntraced(function* (port: VoicePort) {
}

yield* Ref.set(stalled, 0);
yield* Effect.raceFirst(
reaches(voice.connection, VoiceConnectionStatus.Disconnected),
reaches(voice.connection, VoiceConnectionStatus.Destroyed),
);
yield* leavesReady(voice.connection);

if (!isLive(voice.connection)) return;

if (!(yield* recovers(voice.connection)))
if (isDisconnected(voice.connection) && !(yield* recovers(voice.connection)))
return yield* replace(voice, connectionStep(voice.connection.state));
}
});
Expand Down
Loading