| 1 | import type { Readable } from 'node:stream'; |
| 2 | import { type Database, |
| 3 | import { |
| 4 | Inject, |
| 5 | Injectable, |
| 6 | Logger, |
| 7 | type OnApplicationBootstrap, |
| 8 | type OnApplicationShutdown, |
| 9 | } from '@nestjs/common'; |
| 10 | import { and, eq |
| 11 | |
| 12 | import { DATABASE } |
| 13 | import { |
| 14 | ATTACHMENT_EXTENSIONS, |
| 15 | ATTACHMENT_MAX_BYTES, |
| 16 | attachmentKey, |
| 17 | attachmentTypeOf, |
| 18 | } from '../../lib/attachments/attachments.js'; |
| 19 | import { isValidAssetName } |
| 20 | import { formatByteSize } |
| 21 | import { RESERVATION_TTL } |
| 22 | import { ContentLengthRequiredError } |
| 23 | import { InvalidAssetNameError } |
| 24 | import { RepositoryAccessService } |
| 25 | import { S3Service } |
| 26 | import { StorageQuotaService } |
| 27 | import { |
| 28 | AttachmentNotFoundError, |
| 29 | AttachmentNotOctetStreamError, |
| 30 | AttachmentTooLargeError, |
| 31 | AttachmentTypeNotAllowedError, |
| 32 | } from '../../lib/attachments/attachments.errors.js'; |
| 33 | import { errorMessage } |
| 34 | |
| 35 | const SWEEP_INTERVAL_MS = 60 |
| 36 | const SWEEP_BATCH = 100 |
| 37 | |
| 38 | const attachmentColumns = { |
| 39 | id: schema.attachment |
| 40 | name: schema.attachment |
| 41 | contentType: schema.attachment |
| 42 | size: schema.attachment |
| 43 | }; |
| 44 | |
| 45 | /** Files dropped into issue, pull request, comment and release text. Bytes stream straight from the request to object storage and back. */ |
| 46 | @Injectable() |
| 47 | export class AttachmentsService |
| 48 | implements OnApplicationBootstrap |
| 49 | { |
| 50 | private readonly logger |
| 51 | private timer?: |
| 52 | |
| 53 | constructor( |
| 54 | @Inject(DATABASE) |
| 55 | private readonly access |
| 56 | private readonly s3 |
| 57 | private readonly quota |
| 58 | ) {} |
| 59 | |
| 60 | onApplicationBootstrap() { |
| 61 | this.timer = |
| 62 | this.sweep().catch |
| 63 | this.logger.error |
| 64 | ); |
| 65 | }, SWEEP_INTERVAL_MS); |
| 66 | } |
| 67 | |
| 68 | onApplicationShutdown() { |
| 69 | clearInterval(this.timer |
| 70 | } |
| 71 | |
| 72 | /** Anyone who can read the repository may attach, since anyone who can read it may comment. The uploader pays for the bytes. */ |
| 73 | async upload({ |
| 74 | username, |
| 75 | repo, |
| 76 | requesterId, |
| 77 | name, |
| 78 | bodyType, |
| 79 | contentLength, |
| 80 | body, |
| 81 | }: { |
| 82 | username: string |
| 83 | repo: string |
| 84 | requesterId: string |
| 85 | name: string |
| 86 | /** The request's own `Content-Type`. */ |
| 87 | bodyType: string |
| 88 | contentLength: string |
| 89 | body: Readable |
| 90 | }) { |
| 91 | const repository = |
| 92 | username, |
| 93 | repo, |
| 94 | requesterId, |
| 95 | operation: 'read', |
| 96 | }); |
| 97 | // JSON and form bodies are parsed before any handler runs, so their bytes are gone by the time they could be streamed |
| 98 | if (bodyType?.split |
| 99 | throw new AttachmentNotOctetStreamError() |
| 100 | } |
| 101 | const fileName = |
| 102 | if (!isValidAssetName(fileName |
| 103 | const contentType = |
| 104 | if (!contentType) |
| 105 | throw new AttachmentTypeNotAllowedError( |
| 106 | } |
| 107 | |
| 108 | const size = |
| 109 | if (!contentLength || |
| 110 | throw new ContentLengthRequiredError() |
| 111 | } |
| 112 | if (size > |
| 113 | throw new AttachmentTooLargeError( |
| 114 | } |
| 115 | |
| 116 | const [reserved] |
| 117 | { userId: requesterId |
| 118 | 'asset', |
| 119 | size, |
| 120 | (tx) => |
| 121 | tx |
| 122 | .insert(schema.attachment |
| 123 | .values({ |
| 124 | repositoryId: repository.id |
| 125 | name: fileName, |
| 126 | contentType, |
| 127 | size, |
| 128 | uploaderId: requesterId, |
| 129 | }) |
| 130 | .returning({ id: |
| 131 | ); |
| 132 | |
| 133 | const key = |
| 134 | try { |
| 135 | await this.s3 |
| 136 | Key: key, |
| 137 | Body: body, |
| 138 | ContentLength: size, |
| 139 | ContentType: 'application/octet-stream', |
| 140 | }); |
| 141 | } catch (error) |
| 142 | await this.db |
| 143 | .delete(schema.attachment |
| 144 | .where(eq(schema |
| 145 | throw error; |
| 146 | } |
| 147 | |
| 148 | const [uploaded] |
| 149 | .update(schema.attachment |
| 150 | .set({ uploadedAt: |
| 151 | .where(eq(schema |
| 152 | .returning(attachmentColumns); |
| 153 | // the repository was deleted while the bytes were in flight, taking the row with it |
| 154 | if (!uploaded) |
| 155 | await this.s3 |
| 156 | throw new AttachmentNotFoundError() |
| 157 | } |
| 158 | return uploaded; |
| 159 | } |
| 160 | |
| 161 | /** Readable by whoever can read the repository it was attached in, so a private repository's attachments stay private. */ |
| 162 | async download({ |
| 163 | attachmentId, |
| 164 | requesterId, |
| 165 | }: { |
| 166 | attachmentId: string |
| 167 | requesterId?: string |
| 168 | }) { |
| 169 | const [attachment] |
| 170 | .select({ |
| 171 | ...attachmentColumns, |
| 172 | repositoryId: schema.attachment |
| 173 | }) |
| 174 | .from(schema.attachment |
| 175 | .where( |
| 176 | and( |
| 177 | eq(schema.attachment |
| 178 | isNotNull(schema.attachment |
| 179 | ), |
| 180 | ); |
| 181 | if (!attachment) |
| 182 | |
| 183 | await this.access |
| 184 | repositoryId: attachment.repositoryId |
| 185 | requesterId, |
| 186 | operation: 'read', |
| 187 | }); |
| 188 | |
| 189 | const object = |
| 190 | Bucket: this.s3 |
| 191 | Key: attachmentKey(attachment |
| 192 | }); |
| 193 | if (!object.Body |
| 194 | |
| 195 | return { ...attachment |
| 196 | } |
| 197 | |
| 198 | /** Removes attachments no text in their repository mentions once they are a day old: uploads never posted, and those whose comment was edited away or deleted. The grace day covers a draft still being written. */ |
| 199 | async sweep() { |
| 200 | // ponytail: scans each candidate's repository text with strpos; index attachment references if repositories grow past what a seq scan per hour can take. |
| 201 | const mentionedIn = |
| 202 | sql.raw( |
| 203 | `exists (select 1 from ${from} where ${ |
| 204 | ); |
| 205 | const reviewed = |
| 206 | 'join pull_request p on p.id = t.pull_request_id join issue i on i.id = p.issue_id'; |
| 207 | const { rows |
| 208 | id: string |
| 209 | repository_id: string |
| 210 | }>(sql` |
| 211 | select a.id, a.repository_id from ${schema.attachment} a |
| 212 | where a.created_at < now() - ${RESERVATION_TTL} |
| 213 | and (a.uploaded_at is null or not ( |
| 214 | ${mentionedIn('issue t', |
| 215 | or ${mentionedIn('issue_comment t join issue i on i.id = t.issue_id', |
| 216 | or ${mentionedIn(`pull_request_review t ${reviewed |
| 217 | or ${mentionedIn(`pull_request_review_comment t ${reviewed |
| 218 | or ${mentionedIn('release t', |
| 219 | )) |
| 220 | limit ${SWEEP_BATCH} |
| 221 | `); |
| 222 | |
| 223 | for (const row |
| 224 | // bytes first: a row left without its object is swept again, an object left without its row would be kept forever |
| 225 | await this.s3 |
| 226 | Bucket: this.s3 |
| 227 | Key: attachmentKey(row |
| 228 | }); |
| 229 | await this.db |
| 230 | .delete(schema.attachment |
| 231 | .where(eq(schema |
| 232 | } |
| 233 | return rows.length; |
| 234 | } |
| 235 | } |