refactor: events to a pure stream instead of being part of topics

NOTE: tests are passing, but the client is broken
This commit is contained in:
Andy Burke 2025-11-08 11:55:57 -08:00
parent c34069066d
commit a5707e2f81
31 changed files with 934 additions and 686 deletions

View file

@ -0,0 +1,23 @@
# /api/channels/:channel_id
Interact with a specific channel.
## GET /api/channels/:channel_id
Get the channel specified by `:channel_id`.
## PUT /api/channels/:channel_id
Update the channels specified by `:channel_id`.
Eg:
```
{
name?: string;
}
```
## DELETE /api/channels/:channel_id
Delete the channel specified by `:channel_id`.

View file

@ -0,0 +1,40 @@
import { EVENT, EVENTS } from '../../../../../../models/event.ts';
import { CHANNEL, CHANNELS } from '../../../../../../models/channel.ts';
import * as CANNED_RESPONSES from '../../../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../../utils/prechecks.ts';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/channels/:channel_id/events/:id - Get an event
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const channel_id: string = meta.params?.channel_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const channel: CHANNEL | null = channel_id.length === 49 ? await CHANNELS.get(channel_id) : null;
if (!channel) {
return CANNED_RESPONSES.not_found();
}
meta.channel = channel;
const channel_is_public = channel.permissions.read.length === 0;
const user_has_read_for_channel = channel_is_public || channel.permissions.read.includes(meta.user.id);
const channel_has_public_events = user_has_read_for_channel && (channel.permissions.events.read.length === 0);
const user_has_read_events_for_channel = user_has_read_for_channel &&
(channel_has_public_events || channel.permissions.events.read.includes(meta.user.id));
if (!user_has_read_events_for_channel) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const event: EVENT | null = await EVENTS.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
return Response.json(event, {
status: 200
});
}

View file

@ -0,0 +1,134 @@
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts';
import { CHANNEL, CHANNELS } from '../../../../../models/channel.ts';
import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts';
import { EVENT, EVENTS } from '../../../../../models/event.ts';
import { FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/channels/:channel_id/events - get channel events
// query parameters:
// partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted)
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const channel_id: string = meta.params?.channel_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const channel: CHANNEL | null = channel_id.length === 49 ? await CHANNELS.get(channel_id) : null;
if (!channel) {
return CANNED_RESPONSES.not_found();
}
meta.channel = channel;
const channel_is_public: boolean = meta.channel.permissions.read.length === 0;
const user_has_read_for_channel = channel_is_public || meta.channel.permissions.read.includes(meta.user.id);
if (!user_has_read_for_channel) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function GET(request: Request, meta: Record<string, any>): Promise<Response> {
const sorts = EVENTS.sorts;
const sort_name: string = meta.query.sort ?? 'newest';
const key = sort_name as keyof typeof sorts;
const sort: any = sorts[key];
if (!sort) {
return Response.json({
error: {
message: 'You must specify a sort: newest, oldest, latest, stalest',
cause: 'invalid_sort'
}
}, {
status: 400
});
}
const options: FSDB_SEARCH_OPTIONS<EVENT> = {
...(meta.query ?? {}),
limit: Math.min(parseInt(meta.query?.limit ?? '10', 10), 1_000),
offset: Math.max(parseInt(meta.query?.offset ?? '0', 10), 0),
sort,
filter: (entry: WALK_ENTRY<EVENT>) => {
const {
event_type,
event_id
} = /^.*\/(?<event_type>.*?):(?<event_id>[A-Za-z-]+)\.json$/.exec(entry.path)?.groups ?? {};
if (meta.query.after_id && event_id <= meta.query.after_id) {
return false;
}
if (meta.query.before_id && event_id >= meta.query.before_id) {
return false;
}
if (meta.query.type && !meta.query.type.split(',').includes(event_type)) {
return false;
}
return true;
}
};
const headers = {
'Cache-Control': 'no-cache, must-revalidate'
};
const results = (await EVENTS.find({
channel: meta.channel.id
}, options))
.map((entry: WALK_ENTRY<EVENT>) => entry.load())
.sort((lhs_item: EVENT, rhs_item: EVENT) => rhs_item.timestamps.created.localeCompare(lhs_item.timestamps.created));
// long-polling support
if (results.length === 0 && meta.query.wait) {
return new Promise((resolve, reject) => {
function on_create(create_event: any) {
if (create_event.item.channel !== meta.channel.id) {
return;
}
if (meta.query.type && !meta.query.type.split(',').includes(create_event.item.type)) {
return;
}
results.push(create_event.item);
clearTimeout(timeout);
EVENTS.off('create', on_create);
return resolve(Response.json(results, {
status: 200,
headers
}));
}
const timeout = setTimeout(() => {
EVENTS.off('create', on_create);
return resolve(Response.json(results, {
status: 200,
headers
}));
}, 60_000); // 60 seconds
EVENTS.on('create', on_create);
request.signal.addEventListener('abort', () => {
EVENTS.off('create', on_create);
clearTimeout(timeout);
reject(new Error('request aborted'));
});
Deno.addSignalListener('SIGINT', () => {
EVENTS.off('create', on_create);
clearTimeout(timeout);
return resolve(Response.json(results, {
status: 200,
headers
}));
});
});
}
return Response.json(results, {
status: 200,
headers
});
}

View file

@ -1,50 +1,50 @@
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts';
import parse_body from '../../../../utils/bodyparser.ts';
import * as CANNED_RESPONSES from '../../../../utils/canned_responses.ts';
import { TOPIC, TOPICS } from '../../../../models/topic.ts';
import { CHANNEL, CHANNELS } from '../../../../models/channel.ts';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/topics/:id - Get a topic
// GET /api/channels/:id - Get a channel
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
const channel_id: string = meta.params?.channel_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
const channel: CHANNEL | null = channel_id.length === 49 ? await CHANNELS.get(channel_id) : null;
if (!topic) {
if (!channel) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const topic_is_public = topic.permissions.read.length === 0;
const user_has_read_for_topic = topic_is_public || topic.permissions.read.includes(meta.user.id);
meta.channel = channel;
const channel_is_public = channel.permissions.read.length === 0;
const user_has_read_for_channel = channel_is_public || channel.permissions.read.includes(meta.user.id);
if (!user_has_read_for_topic) {
if (!user_has_read_for_channel) {
return CANNED_RESPONSES.permission_denied();
}
}];
export function GET(_req: Request, meta: Record<string, any>): Response {
return Response.json(meta.topic, {
return Response.json(meta.channel, {
status: 200
});
}
// PUT /api/topics/:id - Update topic
// PUT /api/channels/:id - Update channel
PRECHECKS.PUT = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
const channel_id: string = meta.params?.channel_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
const channel: CHANNEL | null = channel_id.length === 49 ? await CHANNELS.get(channel_id) : null;
if (!topic) {
if (!channel) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const user_has_write_for_topic = topic.permissions.write.includes(meta.user.id);
meta.channel = channel;
const user_has_write_for_channel = channel.permissions.write.includes(meta.user.id);
if (!user_has_write_for_topic) {
if (!user_has_write_for_channel) {
return CANNED_RESPONSES.permission_denied();
}
}];
@ -54,16 +54,16 @@ export async function PUT(req: Request, meta: Record<string, any>): Promise<Resp
try {
const body = await parse_body(req);
const updated = {
...meta.topic,
...meta.channel,
...body,
id: meta.topic.id,
id: meta.channel.id,
timestamps: {
created: meta.topic.timestamps.created,
created: meta.channel.timestamps.created,
updated: now
}
};
await TOPICS.update(updated);
await CHANNELS.update(updated);
return Response.json(updated, {
status: 200
});
@ -79,31 +79,31 @@ export async function PUT(req: Request, meta: Record<string, any>): Promise<Resp
}
}
// DELETE /api/topics/:id - Delete topic
// DELETE /api/channels/:id - Delete channel
PRECHECKS.DELETE = [
get_session,
get_user,
require_user,
async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
const channel_id: string = meta.params?.channel_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
const channel: CHANNEL | null = channel_id.length === 49 ? await CHANNELS.get(channel_id) : null;
if (!topic) {
if (!channel) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const user_has_write_for_topic = topic.permissions.write.includes(meta.user.id);
meta.channel = channel;
const user_has_write_for_channel = channel.permissions.write.includes(meta.user.id);
if (!user_has_write_for_topic) {
if (!user_has_write_for_channel) {
return CANNED_RESPONSES.permission_denied();
}
}
];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
await TOPICS.delete(meta.topic);
await CHANNELS.delete(meta.channel);
return Response.json({
deleted: true

View file

@ -3,40 +3,34 @@ import parse_body from '../../../utils/bodyparser.ts';
import { get_session, get_user, require_user } from '../../../utils/prechecks.ts';
import * as CANNED_RESPONSES from '../../../utils/canned_responses.ts';
import { PRECHECK_TABLE } from '../../../utils/prechecks.ts';
import { TOPIC, TOPICS } from '../../../models/topic.ts';
import { WALK_ENTRY } from '@andyburke/fsdb';
import { CHANNEL, CHANNELS } from '../../../models/channel.ts';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/topics - get topics
// GET /api/channels - get channels
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_read_topics = meta.user.permissions.includes('topics.read');
const can_read_channels = meta.user.permissions.includes('channels.read');
if (!can_read_topics) {
if (!can_read_channels) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const limit = Math.min(parseInt(meta.query.limit ?? '100'), 100);
const topics = (await TOPICS.all({
limit,
filter: (entry: WALK_ENTRY<TOPIC>) => {
// we push our event collections into the topics, and fsdb
// doesn't yet filter that out in its all() logic
return entry.path.indexOf('/events/') === -1;
}
const channels = (await CHANNELS.all({
limit
})).map((topic_entry) => topic_entry.load());
return Response.json(topics, {
return Response.json(channels, {
status: 200
});
}
// POST /api/topics - Create a topic
// POST /api/channels - Create a channel
PRECHECKS.POST = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_create_topics = meta.user.permissions.includes('topics.create');
const can_create_channels = meta.user.permissions.includes('channels.create');
if (!can_create_topics) {
if (!can_create_channels) {
return CANNED_RESPONSES.permission_denied();
}
}];
@ -49,8 +43,8 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
if (typeof body.name !== 'string' || body.name.length === 0) {
return Response.json({
error: {
cause: 'missing_topic_name',
message: 'You must specify a unique name for a topic.'
cause: 'missing_channel_name',
message: 'You must specify a unique name for a channel.'
}
}, {
status: 400
@ -60,8 +54,8 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
if (body.name.length > 64) {
return Response.json({
error: {
cause: 'invalid_topic_name',
message: 'topic names must be 64 characters or fewer.'
cause: 'invalid_channel_name',
message: 'channel names must be 64 characters or fewer.'
}
}, {
status: 400
@ -70,29 +64,31 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
const normalized_name = body.name.toLowerCase();
const existing_topic = (await TOPICS.find({
const existing_channel = (await CHANNELS.find({
name: normalized_name
})).shift();
if (existing_topic) {
if (existing_channel) {
return Response.json({
error: {
cause: 'topic_name_conflict',
message: 'There is already a topic with this name.'
cause: 'channel_name_conflict',
message: 'There is already a channel with this name.'
}
}, {
status: 400
});
}
const topic: TOPIC = {
const channel: CHANNEL = {
...body,
id: lurid(),
creator_id: meta.user.id,
permissions: {
read: (body.permissions?.read ?? []),
write: (body.permissions?.write ?? [meta.user.id]),
read_events: (body.permissions?.read_events ?? []),
write_events: (body.permissions?.write_events ?? [])
events: {
read: (body.permissions?.events?.read ?? []),
write: (body.permissions?.events?.write ?? [])
}
},
timestamps: {
created: now,
@ -101,9 +97,9 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}
};
await TOPICS.create(topic);
await CHANNELS.create(channel);
return Response.json(topic, {
return Response.json(channel, {
status: 201
});
} catch (error) {

View file

View file

@ -0,0 +1,159 @@
import { CHANNEL, CHANNELS } from '../../../../models/channel.ts';
import { EVENT, EVENTS } from '../../../../models/event.ts';
import parse_body from '../../../../utils/bodyparser.ts';
import * as CANNED_RESPONSES from '../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user, user_has_write_permission_for_event } from '../../../../utils/prechecks.ts';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/events/:id - Get an event
PRECHECKS.GET = [get_session, get_user, require_user];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const event: EVENT | null = await EVENTS.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
return Response.json(event, {
status: 200
});
}
// PUT /api/events/:event_id - Update event
PRECHECKS.PUT = [
get_session,
get_user,
require_user,
(_req: Request, _meta: Record<string, any>): Response | undefined => {
if (Deno.env.get('APPEND_ONLY_EVENTS')) {
return CANNED_RESPONSES.append_only_events();
}
},
(_req: Request, meta: Record<string, any>): Response | undefined => {
if (!meta.user.permissions.some((permission: string) => permission.indexOf('events.write') === 0)) {
return CANNED_RESPONSES.permission_denied();
}
}
];
export async function PUT(req: Request, meta: Record<string, any>): Promise<Response> {
const now = new Date().toISOString();
try {
const event: EVENT | null = await EVENTS.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
if (event.creator_id !== meta.user.id) {
return CANNED_RESPONSES.permission_denied();
}
const body = await parse_body(req);
const updated: EVENT = {
...event,
...body,
id: event.id,
creator_id: event.creator_id,
channel: event.channel,
timestamps: {
created: event.timestamps.created,
updated: now
}
};
if (updated.channel) {
const channel: CHANNEL | null = await CHANNELS.get(updated.channel);
if (!channel) {
return Response.json({
errors: [{
cause: 'missing_channel',
message: 'No such channel exists.'
}]
}, {
status: 400
});
}
const user_can_write_events_to_channel = channel.permissions.events.write.length === 0 ? true : channel.permissions.events.write.includes(meta.user.id);
if (!user_can_write_events_to_channel) {
return CANNED_RESPONSES.permission_denied();
}
}
if (!user_has_write_permission_for_event(meta.user, updated)) {
return CANNED_RESPONSES.permission_denied();
}
await EVENTS.update(updated);
return Response.json(updated, {
status: 200
});
} catch (err) {
return Response.json({
error: {
message: (err as Error)?.message ?? 'Unknown error due to invalid data.',
cause: (err as Error)?.cause ?? 'invalid_data'
}
}, {
status: 400
});
}
}
// DELETE /api/events/:event_id - Delete event
PRECHECKS.DELETE = [
get_session,
get_user,
require_user,
(_req: Request, _meta: Record<string, any>): Response | undefined => {
if (Deno.env.get('APPEND_ONLY_EVENTS')) {
return CANNED_RESPONSES.append_only_events();
}
},
(_req: Request, meta: Record<string, any>): Response | undefined => {
if (!meta.user.permissions.some((permission: string) => permission.indexOf('events.write') === 0)) {
return CANNED_RESPONSES.permission_denied();
}
}
];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
const event: EVENT | null = await EVENTS.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
if (event.channel) {
const channel: CHANNEL | null = await CHANNELS.get(event.channel);
if (!channel) {
return Response.json({
errors: [{
cause: 'missing_channel',
message: 'No such channel exists.'
}]
}, {
status: 400
});
}
const user_can_write_events_to_channel = channel.permissions.events.write.length === 0 ? true : channel.permissions.events.write.includes(meta.user.id);
if (!user_can_write_events_to_channel) {
return CANNED_RESPONSES.permission_denied();
}
}
if (!user_has_write_permission_for_event(meta.user, event)) {
return CANNED_RESPONSES.permission_denied();
}
await EVENTS.delete(event);
return Response.json({
deleted: true
}, {
status: 200
});
}

View file

@ -1,42 +1,21 @@
import lurid from '@andyburke/lurid';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts';
import { TOPIC, TOPICS } from '../../../../../models/topic.ts';
import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts';
import { EVENT, get_events_collection_for_topic, VALIDATE_EVENT } from '../../../../../models/event.ts';
import parse_body from '../../../../../utils/bodyparser.ts';
import { FSDB_COLLECTION, FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';
import { WATCH, WATCHES } from '../../../../../models/watch.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user, user_has_write_permission_for_event } from '../../../utils/prechecks.ts';
import * as CANNED_RESPONSES from '../../../utils/canned_responses.ts';
import { EVENT, EVENTS, VALIDATE_EVENT } from '../../../models/event.ts';
import parse_body from '../../../utils/bodyparser.ts';
import { FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';
import { WATCH, WATCHES } from '../../../models/watch.ts';
import { flatten } from '../../../utils/object_helpers.ts';
import { CHANNEL, CHANNELS } from '../../../models/channel.ts';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/topics/:topic_id/events - get topic events
// GET /api/events - get events
// query parameters:
// partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted)
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!topic) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const topic_events_are_public = meta.topic.permissions.read_events.length === 0;
const user_has_read_events_for_topic = user_has_read_for_topic &&
(topic_events_are_public || meta.topic.permissions.read_events.includes(meta.user.id));
if (!user_has_read_events_for_topic) {
return CANNED_RESPONSES.permission_denied();
}
}];
PRECHECKS.GET = [get_session, get_user, require_user];
export async function GET(request: Request, meta: Record<string, any>): Promise<Response> {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const sorts = events.sorts;
const sorts = EVENTS.sorts;
const sort_name: string = meta.query.sort ?? 'newest';
const key = sort_name as keyof typeof sorts;
const sort: any = sorts[key];
@ -53,7 +32,7 @@ export async function GET(request: Request, meta: Record<string, any>): Promise<
const options: FSDB_SEARCH_OPTIONS<EVENT> = {
...(meta.query ?? {}),
limit: Math.min(parseInt(meta.query?.limit ?? '10', 10), 1_000),
limit: Math.min(parseInt(meta.query?.limit ?? '100', 10), 1_000),
offset: Math.max(parseInt(meta.query?.offset ?? '0', 10), 0),
sort,
filter: (entry: WALK_ENTRY<EVENT>) => {
@ -82,8 +61,9 @@ export async function GET(request: Request, meta: Record<string, any>): Promise<
'Cache-Control': 'no-cache, must-revalidate'
};
const results = (await events.all(options))
const results = (await EVENTS.all(options))
.map((entry: WALK_ENTRY<EVENT>) => entry.load())
.filter((event) => typeof event.channel === 'undefined') // channel events must be queried via the channel's api
.sort((lhs_item: EVENT, rhs_item: EVENT) => rhs_item.timestamps.created.localeCompare(lhs_item.timestamps.created));
// long-polling support
@ -96,7 +76,7 @@ export async function GET(request: Request, meta: Record<string, any>): Promise<
results.push(create_event.item);
clearTimeout(timeout);
events.off('create', on_create);
EVENTS.off('create', on_create);
return resolve(Response.json(results, {
status: 200,
@ -105,20 +85,20 @@ export async function GET(request: Request, meta: Record<string, any>): Promise<
}
const timeout = setTimeout(() => {
events.off('create', on_create);
EVENTS.off('create', on_create);
return resolve(Response.json(results, {
status: 200,
headers
}));
}, 60_000); // 60 seconds
events.on('create', on_create);
EVENTS.on('create', on_create);
request.signal.addEventListener('abort', () => {
events.off('create', on_create);
EVENTS.off('create', on_create);
clearTimeout(timeout);
reject(new Error('request aborted'));
});
Deno.addSignalListener('SIGINT', () => {
events.off('create', on_create);
EVENTS.off('create', on_create);
clearTimeout(timeout);
return resolve(Response.json(results, {
status: 200,
@ -134,52 +114,78 @@ export async function GET(request: Request, meta: Record<string, any>): Promise<
});
}
async function update_watches(topic: TOPIC, event: EVENT) {
async function update_watches(event: EVENT) {
const limit = 100;
let more_to_process;
let offset = 0;
do {
const watches: WATCH[] = (await WATCHES.find({
topic_id: topic.id
}, {
const watches: WATCH[] = (await WATCHES.all({
limit,
offset
})).map((entry) => entry.load());
// TODO: look at the watch .types[] and send notifications
for (const watch of watches) {
if (typeof watch.type === 'string' && event.type !== watch.type) {
continue;
}
if (typeof watch.parent_id === 'string' && event.parent_id !== watch.parent_id) {
continue;
}
if (typeof watch.channel === 'string' && event.channel !== watch.channel) {
continue;
}
if (typeof watch.topic === 'string' && event.topic !== watch.topic) {
continue;
}
if (typeof watch.tags !== 'undefined' && !watch.tags.every((tag) => event.tags?.includes(tag))) {
continue;
}
if (typeof watch.data !== 'undefined') {
const event_data = flatten(event.data ?? {});
for (const [key, value] of Object.entries(flatten(watch.data))) {
const matcher = new RegExp(value);
if (!matcher.test(event_data[key])) {
continue;
}
}
}
if (event.id < watch.last_id_seen) {
continue;
}
watch.last_id_seen = event.id;
// TODO: send a notification
console.dir({
notification: {
watch,
event
}
});
}
offset += watches.length;
more_to_process = watches.length === limit;
} while (more_to_process);
}
// POST /api/topics/:topic_id/events - Create an event
PRECHECKS.POST = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// POST /api/events - Create an event
PRECHECKS.POST = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const user_can_create_events = meta.user.permissions.some((permission: string) => permission.indexOf('events.create') === 0);
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!topic) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const topic_events_are_publicly_writable = meta.topic.permissions.write_events.length === 0;
const user_has_write_events_for_topic = user_has_read_for_topic &&
(topic_events_are_publicly_writable || meta.topic.permissions.write_events.includes(meta.user.id));
if (!user_has_write_events_for_topic) {
if (!user_can_create_events) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function POST(req: Request, meta: Record<string, any>): Promise<Response> {
try {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const now = new Date().toISOString();
const body = await parse_body(req);
@ -204,7 +210,33 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
});
}
await events.create(event);
if (!user_has_write_permission_for_event(meta.user, event)) {
return CANNED_RESPONSES.permission_denied();
}
if (event.channel) {
const channel: CHANNEL | null = await CHANNELS.get(event.channel);
if (!channel) {
return Response.json({
errors: [{
cause: 'missing_channel',
message: 'No such channel exists.'
}]
}, {
status: 400
});
}
const user_can_write_events_to_channel = channel.permissions.events.write.length === 0 ? true : channel.permissions.events.write.includes(meta.user.id);
if (!user_can_write_events_to_channel) {
return CANNED_RESPONSES.permission_denied();
}
}
await EVENTS.create(event);
update_watches(event);
return Response.json(event, {
status: 201

View file

@ -1,23 +0,0 @@
# /api/topics/:topic_id
Interact with a specific topic.
## GET /api/topics/:topic_id
Get the topic specified by `:topic_id`.
## PUT /api/topics/:topic_id
Update the topics specified by `:topic_id`.
Eg:
```
{
name?: string;
}
```
## DELETE /api/topics/:topic_id
Delete the topic specified by `:topic_id`.

View file

@ -1,166 +0,0 @@
import { FSDB_COLLECTION } from '@andyburke/fsdb';
import { EVENT, get_events_collection_for_topic } from '../../../../../../models/event.ts';
import { TOPIC, TOPICS } from '../../../../../../models/topic.ts';
import parse_body from '../../../../../../utils/bodyparser.ts';
import * as CANNED_RESPONSES from '../../../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../../utils/prechecks.ts';
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/topics/:topic_id/events/:id - Get an event
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!topic) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const topic_is_public = topic.permissions.read.length === 0;
const user_has_read_for_topic = topic_is_public || topic.permissions.read.includes(meta.user.id);
const topic_has_public_events = user_has_read_for_topic && (topic.permissions.read_events.length === 0);
const user_has_read_events_for_topic = user_has_read_for_topic &&
(topic_has_public_events || topic.permissions.read_events.includes(meta.user.id));
if (!user_has_read_events_for_topic) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const event: EVENT | null = await events.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
return Response.json(event, {
status: 200
});
}
// PUT /api/topics/:topic_id/events/:event_id - Update event
PRECHECKS.PUT = [
get_session,
get_user,
require_user,
(_req: Request, _meta: Record<string, any>): Response | undefined => {
if (Deno.env.get('APPEND_ONLY_EVENTS')) {
return CANNED_RESPONSES.append_only_events();
}
},
async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!topic) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const topic_events_are_publicly_writable = meta.topic.permissions.write_events.length === 0;
const user_has_write_events_for_topic = user_has_read_for_topic &&
(topic_events_are_publicly_writable || meta.topic.permissions.write_events.includes(meta.user.id));
if (!user_has_write_events_for_topic) {
return CANNED_RESPONSES.permission_denied();
}
}
];
export async function PUT(req: Request, meta: Record<string, any>): Promise<Response> {
const now = new Date().toISOString();
try {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const event: EVENT | null = await events.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
if (event.creator_id !== meta.user.id) {
return CANNED_RESPONSES.permission_denied();
}
const body = await parse_body(req);
const updated = {
...event,
...body,
id: event.id,
creator_id: event.creator_id,
timestamps: {
created: event.timestamps.created,
updated: now
}
};
await events.update(updated);
return Response.json(updated, {
status: 200
});
} catch (err) {
return Response.json({
error: {
message: (err as Error)?.message ?? 'Unknown error due to invalid data.',
cause: (err as Error)?.cause ?? 'invalid_data'
}
}, {
status: 400
});
}
}
// DELETE /api/topics/:topic_id/events/:event_id - Delete event
PRECHECKS.DELETE = [
get_session,
get_user,
require_user,
(_req: Request, _meta: Record<string, any>): Response | undefined => {
if (Deno.env.get('APPEND_ONLY_EVENTS')) {
return CANNED_RESPONSES.append_only_events();
}
},
async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!topic) {
return CANNED_RESPONSES.not_found();
}
meta.topic = topic;
const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const topic_events_are_publicly_writable = meta.topic.permissions.write_events.length === 0;
const user_has_write_events_for_topic = user_has_read_for_topic &&
(topic_events_are_publicly_writable || meta.topic.permissions.write_events.includes(meta.user.id));
if (!user_has_write_events_for_topic) {
return CANNED_RESPONSES.permission_denied();
}
}
];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const event: EVENT | null = await events.get(meta.params.event_id);
if (!event) {
return CANNED_RESPONSES.not_found();
}
await events.delete(event);
return Response.json({
deleted: true
}, {
status: 200
});
}

View file

@ -1,28 +0,0 @@
# /api/topics
Interact with topics.
## POST /api/topics
Create a new topic.
```
export type TOPIC = {
id: string; // unique id for this topic
name: string; // the name of the topic (max 128 characters)
icon_url?: string; // optional url for a topic icon
topic?: string; // optional topic topic
tags: string[]; // a list of tags for the topic
meta: Record<string, any>;
limits: {
users: number;
user_messages_per_minute: number;
};
creator_id: string; // user_id of the topic creator
emojis: Record<string, string>; // either: string: emoji eg: { 'rofl: 🤣, ... } or { 'rofl': 🤣, 'blap': 'https://somewhere.someplace/image.jpg' }
};
```
## GET /api/topics
Get topics.

View file

@ -12,24 +12,30 @@ import { INVITE_CODE, INVITE_CODES } from '../../../models/invites.ts';
// TODO: figure out a better solution for doling out permissions
const DEFAULT_USER_PERMISSIONS: string[] = [
'events.create.blurb',
'events.create.chat',
'events.create.essay',
'events.create.post',
'events.create.presence',
'events.read.blurb',
'events.read.chat',
'events.read.essay',
'events.read.post',
'events.read.presence',
'events.write.blurb',
'events.write.chat',
'events.write.essay',
'events.write.post',
'events.write.presence',
'files.write.own',
'invites.create',
'invites.read.own',
'self.read',
'self.write',
'signups.read.own',
'topics.read',
'topics.blurbs.create',
'topics.blurbs.read',
'topics.blurbs.write',
'topics.chat.write',
'topics.chat.read',
'topics.essays.create',
'topics.essays.read',
'topics.essays.write',
'topics.posts.create',
'topics.posts.write',
'topics.posts.read',
'users.read',
'watches.create.own',
'watches.read.own',
@ -39,12 +45,12 @@ const DEFAULT_USER_PERMISSIONS: string[] = [
// TODO: figure out a better solution for doling out permissions
const DEFAULT_SUPERUSER_PERMISSIONS: string[] = [
...DEFAULT_USER_PERMISSIONS,
'channels.create',
'channels.delete',
'channels.write',
'files.write.all',
'invites.read.all',
'signups.read.all',
'topics.create',
'topics.delete',
'topics.write',
'users.write',
'watches.read.all',
'watches.write.all'