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
2 changes: 1 addition & 1 deletion src/commands/channel/threads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ describe('channel threads', () => {

await program.parseAsync(['node', 'tdc', 'channel', 'threads', '12345', '--json'])

expect(vi.mocked(assertChannelIsPublic)).toHaveBeenCalledWith('CH100', 1)
expect(vi.mocked(assertChannelIsPublic)).toHaveBeenCalledWith('CH100', 1, true)
})

it('propagates the error when the channel is private and the guard rejects', async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/channel/threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export async function showChannelThreads(
}

const channel = await resolveChannelRef(channelRef, workspaceId)
await assertChannelIsPublic(channel.id, workspaceId)
await assertChannelIsPublic(channel.id, workspaceId, channel.public)

const archived = archiveFilterToFlag(options.archiveFilter)
const client = await getCommsClient()
Expand Down
2 changes: 1 addition & 1 deletion src/commands/thread/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export async function createThread(

const client = await getCommsClient()
const channel = await client.channels.getChannel(channelId)
await assertChannelIsPublic(channelId, channel.workspaceId)
await assertChannelIsPublic(channelId, channel.workspaceId, channel.public)

let resolved: ResolvedNotify | undefined
if (allIds) {
Expand Down
56 changes: 56 additions & 0 deletions src/lib/public-channels.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@ const mockGetCommsClient = vi.mocked(getCommsClient)

function makeMockChannels(
channels: Array<{ id: string; public: boolean }>,
workspacePublicChannels: Array<{ id: string }> = [],
): ReturnType<typeof getCommsClient> {
return Promise.resolve({
channels: {
getChannels: vi.fn().mockResolvedValue(channels),
},
workspaces: {
getPublicChannels: vi.fn().mockResolvedValue(workspacePublicChannels),
},
}) as unknown as ReturnType<typeof getCommsClient>
}

Expand Down Expand Up @@ -161,6 +165,58 @@ describe('assertChannelIsPublic', () => {
await expect(assertChannelIsPublic('CH5', 100)).resolves.toBeUndefined()
})

it("allows a public channel the user hasn't joined", async () => {
mockGetCommsClient.mockImplementation(() =>
makeMockChannels([{ id: 'CH5', public: true }], [{ id: 'CH5' }, { id: 'CH7' }]),
)

await expect(assertChannelIsPublic('CH7', 100)).resolves.toBeUndefined()
})

it('throws for a channel that is neither joined nor public', async () => {
mockGetCommsClient.mockImplementation(() =>
makeMockChannels([{ id: 'CH5', public: true }], [{ id: 'CH5' }, { id: 'CH7' }]),
)

await expect(assertChannelIsPublic('CH9', 100)).rejects.toThrow('private channel')
})

it("only lists the workspace's public channels for a channel the user hasn't joined", async () => {
const getPublicChannels = vi.fn().mockResolvedValue([{ id: 'CH5' }, { id: 'CH7' }])
mockGetCommsClient.mockResolvedValue({
channels: {
getChannels: vi.fn().mockResolvedValue([
{ id: 'CH5', public: true },
{ id: 'CH6', public: false },
]),
},
workspaces: { getPublicChannels },
} as unknown as Awaited<ReturnType<typeof getCommsClient>>)

await assertChannelIsPublic('CH5', 100)
await expect(assertChannelIsPublic('CH6', 100)).rejects.toThrow('private channel')
expect(getPublicChannels).not.toHaveBeenCalled()

await assertChannelIsPublic('CH7', 100)
await assertChannelIsPublic('CH7', 100)
expect(getPublicChannels).toHaveBeenCalledTimes(1)
expect(getPublicChannels).toHaveBeenCalledWith(100)
})

it('uses the public flag a caller passes instead of looking the channel up', async () => {
const getChannels = vi.fn()
const getPublicChannels = vi.fn()
mockGetCommsClient.mockResolvedValue({
channels: { getChannels },
workspaces: { getPublicChannels },
} as unknown as Awaited<ReturnType<typeof getCommsClient>>)

await expect(assertChannelIsPublic('CH7', 100, true)).resolves.toBeUndefined()
await expect(assertChannelIsPublic('CH6', 100, false)).rejects.toThrow('private channel')
expect(getChannels).not.toHaveBeenCalled()
expect(getPublicChannels).not.toHaveBeenCalled()
})

it('allows private channels when --include-private-channels is set', async () => {
process.argv = ['node', 'tdc', '--include-private-channels']
resetGlobalArgs()
Expand Down
59 changes: 47 additions & 12 deletions src/lib/public-channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,65 @@ import { getCommsClient } from './api.js'
import { CliError } from './errors.js'
import { includePrivateChannels } from './global-args.js'

const publicChannelCache = new Map<number, Set<string>>()
// Channel ID to whether it's public, for the channels the user has joined.
const joinedChannelCache = new Map<number, Map<string, boolean>>()
const workspacePublicChannelCache = new Map<number, Set<string>>()

export async function getPublicChannelIds(workspaceId: number): Promise<Set<string>> {
const cached = publicChannelCache.get(workspaceId)
async function getJoinedChannels(workspaceId: number): Promise<Map<string, boolean>> {
const cached = joinedChannelCache.get(workspaceId)
if (cached) return cached

const client = await getCommsClient()
const channels = await client.channels.getChannels({ workspaceId })
const publicIds = new Set<string>()
for (const ch of channels) {
if (ch.public) publicIds.add(ch.id)
}
publicChannelCache.set(workspaceId, publicIds)
const joined = new Map(channels.map((ch) => [ch.id, ch.public]))
joinedChannelCache.set(workspaceId, joined)
return joined
}

/** IDs of the public channels the user has joined. */
export async function getPublicChannelIds(workspaceId: number): Promise<Set<string>> {
const joined = await getJoinedChannels(workspaceId)
return new Set([...joined].filter(([, isPublic]) => isPublic).map(([id]) => id))
}

// Every public channel in the workspace, joined or not. Much bigger than the joined list (all
// members of every public channel) and empty for guests, so it's only used for unjoined channels.
async function getWorkspacePublicChannelIds(workspaceId: number): Promise<Set<string>> {
const cached = workspacePublicChannelCache.get(workspaceId)
if (cached) return cached

const client = await getCommsClient()
const channels = await client.workspaces.getPublicChannels(workspaceId)
const publicIds = new Set(channels.map((ch) => ch.id))
workspacePublicChannelCache.set(workspaceId, publicIds)
return publicIds
}

export function clearPublicChannelCache(): void {
publicChannelCache.clear()
joinedChannelCache.clear()
workspacePublicChannelCache.clear()
}

async function isPublicChannel(channelId: string, workspaceId: number): Promise<boolean> {
const joined = await getJoinedChannels(workspaceId)
return (
joined.get(channelId) ??
// getChannels only returns joined channels, so an unjoined one could still be public.
(await getWorkspacePublicChannelIds(workspaceId)).has(channelId)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the workspace's public channels and not getChannel for just this one: channels/getone is the call with the per-user rate limit (see #94), and thread view already makes one for the channel name. The public channel list has no limit but is much bigger, since it carries every public channel's members: about 0.3s extra on an unjoined channel in a quick timing (1.31s against 0.98s for a joined one). It's only fetched when the channel isn't one you've joined, once per run. It also comes back empty for guests, so it can only be a fallback, not a replacement for the joined list.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 For tdc channel threads <name> resolving to an unjoined public channel, this fallback fetches workspaces.getPublicChannels again right after resolveChannelRef in src/lib/refs.ts has already fetched the same list to resolve the name (channels.getChannels is also fetched by both paths). That doubles the heaviest call on the exact path this PR enables — the list the PR otherwise treats as expensive. showChannelThreads already has the resolved Channel with its public flag, so pass that known value into assertChannelIsPublic (or otherwise share the public-channel cache) to avoid the duplicate fetch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 3d6924d, and in thread create too.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Reuse thread view's existing channel lookup. viewThread calls this guard before unconditionally fetching client.channels.getChannel(thread.channelId) for the channel name. For an unjoined public channel, it therefore downloads the workspace-wide public-channel list, including channel members, even though the subsequent channel lookup supplies the same visibility flag. Move that existing lookup before the guard and pass channel.public; this avoids the new workspace-wide request without adding another rate-limited getChannel call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this one. Thread view's channel lookup is the rate-limited call, and #94 is making a 429 there show the thread without the channel name instead of failing. If the private-channel check relied on that lookup, those views would fail again. The list call only runs for channels you haven't joined, about 0.3s there. Once #94 is in, the lookup could feed the check, with the list as the fallback on a 429.

)
}

export async function assertChannelIsPublic(channelId: string, workspaceId: number): Promise<void> {
/**
* Throws unless the channel is public or --include-private-channels is set. Callers that
* already have the channel pass its `public` flag, which skips the lookups.
*/
export async function assertChannelIsPublic(
channelId: string,
workspaceId: number,
isPublic?: boolean,
): Promise<void> {
if (includePrivateChannels()) return
const publicIds = await getPublicChannelIds(workspaceId)
if (!publicIds.has(channelId)) {
if (!(isPublic ?? (await isPublicChannel(channelId, workspaceId)))) {
throw new CliError('NOT_FOUND', 'This thread belongs to a private channel.', [
'Use --include-private-channels to access it',
])
Expand Down
Loading