forge
Explore
Log in

Don't you dare go Hollow

The podcast report/upload handshake over a real QUIC stream

Browse files at this commit

61960a537d77a3a824212a8753ef65766f27d075Ahmet Kaan GümüşParent: c44f362
  • test
    • the podcast report/upload handshake over a real QUIC stream
Show full message
🧪 test(bridge): the podcast report/upload handshake over a real QUIC stream

Three bridge-level tests for the podcast job's own rows, driven through real
client-initiated frames against a live bridge: the running/done/refused report
sequence with the row re-read after each refusal, the upload landing the exact
bytes under the school's own blob directory and stamping audio_key +
duration_secs (done accepted only after it), and the two-school test proving
the frame's school — not the payload — decides which database a report or an
upload can touch (no bytes under the other school, its row untouched).
`an_upload_past_the_audio_ceiling_is_refused_before_a_byte_is_read` sends no
body on purpose: the refusal must come off the frame alone.
tests/ai_bridge.rsmodified+316 -2
@@ -3511,11 +3511,13 @@ async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() {
35113511 // Everything below rides a real client-initiated QUIC stream, like the api
35123512 // read it is shaped after.
35133513
3514-use hezarfen_backend::ai::protocol::{CapabilityRequest, CapabilityResponse};
3514+use hezarfen_backend::ai::protocol::{
3515+ BlobUploadRequest, BlobUploadResponse, CapabilityRequest, CapabilityResponse,
3516+};
35153517 use hezarfen_backend::constant::{
35163518 AI_INSIGHT_PENDING_LIST_CAPABILITY, AI_INSIGHT_RETENTION_SWEEP_CAPABILITY,
35173519 AI_INSIGHT_RUN_UPSERT_CAPABILITY, AI_INSIGHT_SCHOOLS_LIST_CAPABILITY,
3518- AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3520+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, AI_PODCAST_REPORT_CAPABILITY, PODCAST_AUDIO_MAX_BYTES,
35193521 };
35203522 use hezarfen_backend::domain::user::{Password, Username};
35213523 use hezarfen_backend::service::builder;
@@ -3952,3 +3954,315 @@ async fn the_storage_doors_are_manager_only_and_write_the_callers_own_school() {
39523954 assert_eq!(kept.status, StatusCode::OK);
39533955 assert_eq!(kept.body["summary"]["marks"]["ortalama"], 72);
39543956 }
3957+
3958+// ------------------------------------------------------ the podcast job rows --
3959+//
3960+// The podcast service owns nothing but its pipeline: the job row, its state
3961+// and the produced audio are the backend's. The service reports each
3962+// transition through a `podcast.report` capability call and streams the
3963+// finished mp3 as a `BlobUploadRequest`; both ride real client-initiated QUIC
3964+// streams below, and the two-school test is the one that proves the frame's
3965+// school — never anything the payload says — decides which database a report
3966+// or an upload can touch.
3967+
3968+/// Seed one `queued` job and its submitting user in `db`, returning both ids.
3969+async fn seed_podcast_job(db: &Database) -> (String, String) {
3970+ let user = hezarfen_backend::domain::monotonic_id::next_uuid();
3971+ sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
3972+ .bind(user)
3973+ .bind(format!("podcaster-{}", &user.simple().to_string()[..12]))
3974+ .execute(db)
3975+ .await
3976+ .expect("insert the submitter");
3977+ let job = hezarfen_backend::domain::monotonic_id::next_uuid();
3978+ let now = hezarfen_backend::domain::timestamp::Timestamp::now().as_millis();
3979+ sqlx::query(
3980+ "INSERT INTO podcast_job (id, user_id, source_id, state, stage, progress, \
3981+ created_at, updated_at) VALUES ($1, $2, 'kaynak-1', 'queued', '', 0, $3, $3)",
3982+ )
3983+ .bind(job)
3984+ .bind(user)
3985+ .bind(now)
3986+ .execute(db)
3987+ .await
3988+ .expect("insert the job");
3989+ (job.to_string(), user.to_string())
3990+}
3991+
3992+/// The row's own answers to what the tests ask of it:
3993+/// (state, stage, progress, audio_key, duration_secs).
3994+async fn podcast_row(
3995+ db: &Database,
3996+ job: &str,
3997+) -> (String, String, f64, Option<String>, Option<f64>) {
3998+ use sqlx::Row as _;
3999+ let row = sqlx::query(
4000+ "SELECT state, stage, progress, audio_key, duration_secs FROM podcast_job WHERE id = $1",
4001+ )
4002+ .bind(uuid::Uuid::parse_str(job).expect("a job uuid"))
4003+ .fetch_one(db)
4004+ .await
4005+ .expect("the job row");
4006+ (
4007+ row.get("state"),
4008+ row.get("stage"),
4009+ row.get("progress"),
4010+ row.get("audio_key"),
4011+ row.get("duration_secs"),
4012+ )
4013+}
4014+
4015+fn report_call(
4016+ school: &str,
4017+ job: &str,
4018+ user: &str,
4019+ state: &str,
4020+ stage: &str,
4021+ progress: f64,
4022+) -> CapabilityRequest {
4023+ CapabilityRequest {
4024+ id: format!("trace-report-{job}-{state}"),
4025+ school: school.to_string(),
4026+ capability: AI_PODCAST_REPORT_CAPABILITY.to_string(),
4027+ payload: json!({
4028+ "job_id": job,
4029+ "source_id": "kaynak-1",
4030+ "format": "duz_okuma",
4031+ "user_id": user,
4032+ "state": state,
4033+ "stage": stage,
4034+ "progress": progress,
4035+ }),
4036+ }
4037+}
4038+
4039+/// One upload: the frame, then exactly `size` raw bytes, then FIN — the shape
4040+/// a service writes when it hands back a produced episode.
4041+async fn podcast_upload(
4042+ conn: &quinn::Connection,
4043+ school: &str,
4044+ job: &str,
4045+ name: &str,
4046+ content_type: &str,
4047+ body: &[u8],
4048+) -> BlobUploadResponse {
4049+ let (mut send, mut recv) = conn.open_bi().await.expect("upload stream");
4050+ let request = BlobUploadRequest {
4051+ id: format!("trace-upload-{job}"),
4052+ upload: true,
4053+ school: school.to_string(),
4054+ job_id: job.to_string(),
4055+ name: name.to_string(),
4056+ content_type: content_type.to_string(),
4057+ size: body.len() as u64,
4058+ duration_secs: Some(12.5),
4059+ };
4060+ write_frame(&mut send, &request)
4061+ .await
4062+ .expect("write BlobUploadRequest");
4063+ send.write_all(body).await.expect("write the bytes");
4064+ let _ = send.finish();
4065+ read_frame(&mut recv).await.expect("read BlobUploadResponse")
4066+}
4067+
4068+fn upload_key(answer: BlobUploadResponse) -> (String, u64) {
4069+ match answer {
4070+ BlobUploadResponse::Ok { key, size, .. } => (key, size),
4071+ BlobUploadResponse::Err { code, message, .. } => {
4072+ panic!("expected the bytes to be stored, got {code}: {message}")
4073+ }
4074+ }
4075+}
4076+
4077+fn upload_refusal(answer: BlobUploadResponse) -> (String, String) {
4078+ match answer {
4079+ BlobUploadResponse::Err { code, message, .. } => (code, message),
4080+ BlobUploadResponse::Ok { key, .. } => panic!("expected a refusal, got key {key}"),
4081+ }
4082+}
4083+
4084+/// The whole ingest handshake over the bridge: running reports land on the
4085+/// backend's row, a done report before the upload is refused `audio_missing`,
4086+/// the upload stores the exact bytes under the school's own directory, and
4087+/// only then can the job be finished. Bad echoes and illegal transitions are
4088+/// refused without writing anything.
4089+#[tokio::test]
4090+async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
4091+ let bridge = bridge().await;
4092+ let service = connect_service(
4093+ &bridge,
4094+ hello("podcaster", &["podcast.submit"]),
4095+ Behaviour::Echo,
4096+ )
4097+ .await;
4098+ await_workers(&bridge, 1).await;
4099+ let (_app, db) = common::app_with_ai(Some(bridge.clone())).await;
4100+ let (job, user) = seed_podcast_job(&db).await;
4101+ let conn = &service.conn;
4102+
4103+ let answer = capability_call(
4104+ conn,
4105+ report_call(DEMO_SLUG, &job, &user, "running", "script", 0.5),
4106+ )
4107+ .await;
4108+ assert_eq!(ok_capability(answer)["job_id"], job);
4109+ assert_eq!(podcast_row(&db, &job).await.0, "running");
4110+ assert_eq!(podcast_row(&db, &job).await.1, "script");
4111+
4112+ // `done` means a stored episode: a report that claims one before the
4113+ // upload is refused, and nothing about the row moves.
4114+ let (code, _) = refused_capability(
4115+ capability_call(conn, report_call(DEMO_SLUG, &job, &user, "done", "done", 1.0)).await,
4116+ );
4117+ assert_eq!(code, "audio_missing");
4118+ assert_eq!(podcast_row(&db, &job).await.0, "running");
4119+
4120+ // A report that names another user is refused; the row is untouched.
4121+ let (code, _) = refused_capability(
4122+ capability_call(
4123+ conn,
4124+ report_call(
4125+ DEMO_SLUG,
4126+ &job,
4127+ "00000000-0000-7000-8000-000000000000",
4128+ "failed",
4129+ "",
4130+ 0.0,
4131+ ),
4132+ )
4133+ .await,
4134+ );
4135+ assert_eq!(code, "not_permitted");
4136+ // And so is a transition the service's own table forbids.
4137+ let (code, _) = refused_capability(
4138+ capability_call(conn, report_call(DEMO_SLUG, &job, &user, "queued", "", 0.0)).await,
4139+ );
4140+ assert_eq!(code, "invalid_payload");
4141+ assert_eq!(podcast_row(&db, &job).await.0, "running");
4142+
4143+ // The upload: bytes on disk exactly as sent, key keyed by the job id, row
4144+ // stamped with the reference and the duration.
4145+ let body = blob_bytes(200 * 1024);
4146+ let (key, size) = upload_key(
4147+ podcast_upload(conn, DEMO_SLUG, &job, "bolum.mp3", "audio/mpeg", &body).await,
4148+ );
4149+ assert_eq!(size, body.len() as u64);
4150+ assert_eq!(key, format!("podcast/{job}.mp3"));
4151+ let stored = common::files_dir().join(DEMO_SLUG).join(&key);
4152+ assert_eq!(std::fs::read(&stored).expect("the stored episode"), body);
4153+ let row = podcast_row(&db, &job).await;
4154+ assert_eq!(row.3.as_deref(), Some(key.as_str()));
4155+ assert_eq!(row.4, Some(12.5));
4156+
4157+ // Now — and only now — `done` is accepted.
4158+ assert_eq!(
4159+ ok_capability(
4160+ capability_call(conn, report_call(DEMO_SLUG, &job, &user, "done", "done", 1.0)).await
4161+ )["stored"],
4162+ true
4163+ );
4164+ assert_eq!(podcast_row(&db, &job).await.0, "done");
4165+
4166+ // And a job the backend never minted is `unknown_job`.
4167+ let stranger = hezarfen_backend::domain::monotonic_id::next_uuid().to_string();
4168+ let (code, _) = refused_capability(
4169+ capability_call(conn, report_call(DEMO_SLUG, &stranger, &user, "running", "ocr", 0.1))
4170+ .await,
4171+ );
4172+ assert_eq!(code, "unknown_job");
4173+}
4174+
4175+/// The frame's school decides the database, and nothing else: a report or an
4176+/// upload naming the demo school cannot reach a job that lives in beta's.
4177+#[tokio::test]
4178+async fn a_report_or_upload_cannot_reach_another_schools_job() {
4179+ let bridge = bridge().await;
4180+ let service = connect_service(
4181+ &bridge,
4182+ hello("podcaster", &["podcast.submit"]),
4183+ Behaviour::Echo,
4184+ )
4185+ .await;
4186+ await_workers(&bridge, 1).await;
4187+ let (_app, _demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
4188+ let beta = Slug::try_new("beta").unwrap();
4189+ let beta_db = tenants
4190+ .create(
4191+ hezarfen_backend::tenant::SchoolId::generate(),
4192+ &beta,
4193+ "Beta College",
4194+ ModuleSet::all(),
4195+ )
4196+ .await
4197+ .expect("beta");
4198+ let (job, user) = seed_podcast_job(&beta_db).await;
4199+
4200+ let (code, _) = refused_capability(
4201+ capability_call(
4202+ &service.conn,
4203+ report_call(DEMO_SLUG, &job, &user, "running", "script", 0.2),
4204+ )
4205+ .await,
4206+ );
4207+ assert_eq!(code, "unknown_job");
4208+ assert_eq!(
4209+ podcast_row(&beta_db, &job).await.0,
4210+ "queued",
4211+ "beta's row is untouched by a frame that named demo"
4212+ );
4213+
4214+ let body = blob_bytes(4096);
4215+ let (code, _) = upload_refusal(
4216+ podcast_upload(&service.conn, DEMO_SLUG, &job, "bolum.mp3", "audio/mpeg", &body).await,
4217+ );
4218+ assert_eq!(code, "unknown_job");
4219+ let leaked = common::files_dir()
4220+ .join(DEMO_SLUG)
4221+ .join(format!("podcast/{job}.mp3"));
4222+ assert!(
4223+ !leaked.exists(),
4224+ "no bytes may land under a school the job does not belong to"
4225+ );
4226+ assert!(
4227+ podcast_row(&beta_db, &job).await.3.is_none(),
4228+ "beta's row names no audio"
4229+ );
4230+}
4231+
4232+/// The size ceiling is a refusal before a byte is read: the frame alone is
4233+/// enough to refuse it, so a backend that read first would park the stream
4234+/// instead of answering. The client here never sends a body on purpose.
4235+#[tokio::test]
4236+async fn an_upload_past_the_audio_ceiling_is_refused_before_a_byte_is_read() {
4237+ let bridge = bridge().await;
4238+ let service = connect_service(
4239+ &bridge,
4240+ hello("podcaster", &["podcast.submit"]),
4241+ Behaviour::Echo,
4242+ )
4243+ .await;
4244+ await_workers(&bridge, 1).await;
4245+ let (_app, db) = common::app_with_ai(Some(bridge.clone())).await;
4246+ let (job, _user) = seed_podcast_job(&db).await;
4247+
4248+ let (mut send, mut recv) = service.conn.open_bi().await.expect("upload stream");
4249+ let request = BlobUploadRequest {
4250+ id: "trace-oversize".to_string(),
4251+ upload: true,
4252+ school: DEMO_SLUG.to_string(),
4253+ job_id: job.clone(),
4254+ name: "bolum.mp3".to_string(),
4255+ content_type: "audio/mpeg".to_string(),
4256+ size: PODCAST_AUDIO_MAX_BYTES as u64 + 1,
4257+ duration_secs: None,
4258+ };
4259+ write_frame(&mut send, &request).await.expect("write the frame");
4260+ let answer: BlobUploadResponse = read_frame(&mut recv).await.expect("read the answer");
4261+ let (code, _) = upload_refusal(answer);
4262+ assert_eq!(code, "invalid_payload");
4263+ let _ = send.finish();
4264+
4265+ assert!(podcast_row(&db, &job).await.3.is_none(), "the row names no audio");
4266+ let stored = common::files_dir().join(format!("podcast/{job}.mp3"));
4267+ assert!(!stored.exists(), "an oversize upload stores nothing");
4268+}