assay-lua 0.20.0

General-purpose enhanced Lua runtime. Batteries-included scripting, automation, and web services.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! ContactOut and BetterContact against recorded response shapes. The live
//! smoke test waits on keys; what can be pinned without one is pinned here —
//! the auth header each vendor wants, the gate being unbypassable, an async
//! run only counting as finished when it says so, and vendor claims never
//! laundering into VERIFIED.

#[path = "../common/mod.rs"]
mod common;

use common::run_lua;
use serde_json::json;
use wiremock::matchers::{header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Approves everything and records what it was asked to spend.
const OPEN_GATE: &str = r#"
local lp = require("assay.lead_provider")
local spent = {}
local gate = lp.gate({
  approve = function(op, cents) spent[#spent + 1] = op .. ":" .. cents; return true end,
  meter = function() end,
})
"#;

/// Refuses everything, so a test can prove the vendor is never called.
const CLOSED_GATE: &str = r#"
local lp = require("assay.lead_provider")
local gate = lp.gate({
  approve = function() return false, "over_cap" end,
  meter = function() end,
})
"#;

fn script(gate: &str, module: &str, alias: &str, ctor: &str, uri: &str, body: &str) -> String {
    format!(
        "{gate}\nlocal {alias} = require(\"assay.{module}\")\n\
         local c = {alias}.client(gate, {{ {ctor}, base_url = \"{uri}\" }})\n{body}"
    )
}

async fn contactout(uri: &str, body: &str) -> Result<(), mlua::Error> {
    run_lua(&script(OPEN_GATE, "contactout", "co", r#"token = "k""#, uri, body)).await
}

/// Runs a ContactOut script against the mock server and expects it to pass.
async fn co_ok(server: &MockServer, body: &str) {
    contactout(&server.uri(), body).await.unwrap();
}

async fn bettercontact(gate: &str, uri: &str, body: &str) -> Result<(), mlua::Error> {
    run_lua(&script(gate, "bettercontact", "bc", r#"api_key = "bc-key""#, uri, body)).await
}

async fn server_returning(m: &str, p: &str, status: u16) -> MockServer {
    let server = MockServer::start().await;
    let mock = if m == "POST" {
        Mock::given(method("POST")).and(path(p.to_string()))
    } else {
        Mock::given(method("GET")).and(path(p.to_string()))
    };
    mock.respond_with(ResponseTemplate::new(status)).mount(&server).await;
    server
}

fn assert_says(err: mlua::Error, want: &str, ctx: &str) {
    let text = err.to_string();
    assert!(text.contains(want), "{ctx} gave {text}, wanted {want}");
}

// ---------------------------------------------------------------------------
// ContactOut
// ---------------------------------------------------------------------------

fn profile_response(profile: serde_json::Value) -> ResponseTemplate {
    ResponseTemplate::new(200).set_body_json(json!({ "status_code": 200, "profile": profile }))
}

/// The header is the bare name `token` — not `Authorization`, no `Bearer`.
/// Getting it wrong reads as an invalid key rather than a malformed request.
#[tokio::test]
async fn test_contactout_sends_the_bare_token_header() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/linkedin/enrich"))
        .and(header("token", "k"))
        .respond_with(profile_response(json!({
            "url": "https://www.linkedin.com/in/jchurch",
            "full_name": "Jonathan Church",
            "headline": "Managing Director",
            "work_email": ["jonathan.church@cheaney.co.uk"],
            "email": ["jonathan.church@cheaney.co.uk", "jc@personal.example"]
        })))
        .mount(&server)
        .await;
    co_ok(
        &server,
        r#"
        local p = c:enrich_linkedin("https://www.linkedin.com/in/jchurch")
        assert.eq(p.full_name, "Jonathan Church")
        assert.eq(p.first_name, "Jonathan")
        assert.eq(p.last_name, "Church")
        assert.eq(p.title, "Managing Director")
        assert.eq(#p.emails, 2)
        assert.eq(p.emails[1].address, "jonathan.church@cheaney.co.uk")
        assert.eq(p.emails[1].verification_status, "UNKNOWN")
        assert.eq(p.provenance.provider, "contactout")
        assert.not_nil(p.provenance.retrieved_at)
        assert.eq(spent[1], "find_person:0")
        "#,
    )
    .await;
}

/// Work email leads even when the general list repeats it: outbound writes to
/// a desk, not to someone's personal address.
#[tokio::test]
async fn test_contactout_puts_work_email_first_without_duplicating_it() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/people/person"))
        .and(query_param("email", "jc@cheaney.co.uk"))
        .respond_with(profile_response(json!({
            "email": ["jc@cheaney.co.uk"],
            "work_email": ["jc@cheaney.co.uk"],
            "linkedin": "https://www.linkedin.com/in/jc"
        })))
        .mount(&server)
        .await;
    co_ok(
        &server,
        r#"
        local p = c:profile_by_email("jc@cheaney.co.uk")
        assert.eq(#p.emails, 1)
        assert.eq(p.linkedin, "https://www.linkedin.com/in/jc")
        "#,
    )
    .await;
}

async fn mount_enrich_expecting(server: &MockServer, body: serde_json::Value) {
    Mock::given(method("POST"))
        .and(path("/v1/people/enrich"))
        .and(wiremock::matchers::body_json(body))
        .respond_with(profile_response(json!({ "full_name": "Jonathan Church" })))
        .mount(server)
        .await;
}

/// The live enrich endpoint 400s on a string `company` — it must be a JSON
/// array, and an absent one must be omitted, not sent empty.
#[tokio::test]
async fn test_contactout_sends_company_as_an_array_and_omits_it_when_absent() {
    let server = MockServer::start().await;
    mount_enrich_expecting(
        &server,
        json!({
            "full_name": "Jonathan Church",
            "company": ["Joseph Cheaney & Sons"],
            "include": ["work_email"]
        }),
    )
    .await;
    mount_enrich_expecting(
        &server,
        json!({ "full_name": "Jonathan Church", "include": ["work_email"] }),
    )
    .await;
    co_ok(
        &server,
        r#"
        local with = c:find_person({ full_name = "Jonathan Church", company = "Joseph Cheaney & Sons" })
        assert.eq(with.full_name, "Jonathan Church")
        local without = c:find_person({ full_name = "Jonathan Church" })
        assert.eq(without.full_name, "Jonathan Church")
        "#,
    )
    .await;
}

/// Live responses carry `company` as an object; the person must get its name
/// and domain, not a table.
#[tokio::test]
async fn test_contactout_maps_the_company_object_to_name_and_domain() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/people/person"))
        .respond_with(profile_response(json!({
            "full_name": "Jonathan Church",
            "company": {
                "name": "Joseph Cheaney & Sons",
                "domain": "cheaney.co.uk",
                "email_domain": "cheaney.co.uk"
            }
        })))
        .mount(&server)
        .await;
    co_ok(
        &server,
        r#"
        local p = c:profile_by_email("jc@cheaney.co.uk")
        assert.eq(p.company, "Joseph Cheaney & Sons")
        assert.eq(p.domain, "cheaney.co.uk")
        "#,
    )
    .await;
}

#[tokio::test]
async fn test_contactout_reports_an_unknown_person_as_nil_not_an_error() {
    let server = server_returning("GET", "/v1/linkedin/enrich", 404).await;
    co_ok(
        &server,
        r#"assert.eq(c:enrich_linkedin("https://www.linkedin.com/in/nobody"), nil)"#,
    )
    .await;
}

/// A rejected key and an exhausted quota must not read as "no such person".
#[tokio::test]
async fn test_contactout_distinguishes_auth_and_rate_limit_from_absence() {
    for (status, want) in [(401u16, "rejected the token"), (429, "rate limited")] {
        let server = server_returning("GET", "/v1/linkedin/enrich", status).await;
        let err = contactout(&server.uri(), r#"c:enrich_linkedin("https://x/in/y")"#)
            .await
            .unwrap_err();
        assert_says(err, want, &format!("HTTP {status}"));
    }
}

/// A client buildable without a gate makes an unmetered paid call reachable
/// by omission.
#[tokio::test]
async fn test_contactout_refuses_to_build_without_a_gate_or_a_token() {
    for (args, want) in [
        (r#"nil, { token = "k" }"#, "gate is required"),
        (r#"{}, { token = "k" }"#, "gate is required"),
        (r#"gate, { token = "" }"#, "token required"),
    ] {
        let err = run_lua(&format!(
            "{OPEN_GATE}\nlocal co = require(\"assay.contactout\")\nco.client({args})"
        ))
        .await
        .unwrap_err();
        assert_says(err, want, args);
    }
}

// ---------------------------------------------------------------------------
// BetterContact
// ---------------------------------------------------------------------------

const RUN_ID: &str = "fefbc2203558eb3adcea";

async fn mount_submit(server: &MockServer) {
    Mock::given(method("POST"))
        .and(path("/async"))
        .and(header("x-api-key", "bc-key"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "success": true, "id": RUN_ID, "message": "Processing..."
        })))
        .mount(server)
        .await;
}

async fn mount_result(server: &MockServer, status: u16, body: serde_json::Value) {
    Mock::given(method("GET"))
        .and(path(format!("/async/{RUN_ID}")))
        .respond_with(ResponseTemplate::new(status).set_body_json(body))
        .mount(server)
        .await;
}

async fn run_server(status: u16, body: serde_json::Value) -> MockServer {
    let server = MockServer::start().await;
    mount_submit(&server).await;
    mount_result(&server, status, body).await;
    server
}

#[tokio::test]
async fn test_bettercontact_submits_then_reads_the_terminated_run() {
    let server = run_server(
        200,
        json!({
            "id": RUN_ID, "status": "terminated",
            "credits_consumed": 1, "credits_left": 331,
            "summary": { "total": 1, "valid": 1 },
            "data": [{
                "contact_first_name": "Jonathan",
                "contact_last_name": "Church",
                "contact_full_name": "Jonathan Church",
                "contact_email_address_provider": "dropcontact",
                "contact_job_title": "Managing Director",
                "contact_email_address": "jonathan.church@cheaney.co.uk",
                "contact_email_address_status": "deliverable",
                "company_name": "Joseph Cheaney & Sons",
                "company_domain": "cheaney.co.uk",
                "contact_location_country": "United Kingdom"
            }]
        }),
    )
    .await;
    bettercontact(
        OPEN_GATE,
        &server.uri(),
        r#"
        local p = c:find_person({ first_name = "Jonathan", last_name = "Church",
          domain = "cheaney.co.uk" }, { poll_ms = 1, attempts = 3 })
        assert.eq(p.full_name, "Jonathan Church")
        assert.eq(p.company, "Joseph Cheaney & Sons")
        assert.eq(p.domain, "cheaney.co.uk")
        assert.eq(#p.emails, 1)
        assert.eq(p.emails[1].address, "jonathan.church@cheaney.co.uk")
        assert.eq(p.emails[1].verification_status, "PROBABLE")
        assert.eq(p.emails[1].vendor_status, "deliverable")
        assert.eq(p.emails[1].provider_used, "dropcontact")
        assert.eq(p.provenance.provider, "bettercontact")
        assert.eq(spent[1], "find_person:0")
        "#,
    )
    .await
    .unwrap();
}

/// `valid` from a vendor is an assertion, not a delivery, so it stops at
/// PROBABLE. Only a real send earns VERIFIED (NEP-0007 §2).
#[tokio::test]
async fn test_bettercontact_never_launders_a_vendor_claim_into_verified() {
    for (vendor, want) in [
        ("deliverable", "PROBABLE"),
        ("catch_all", "CATCH_ALL"),
        ("catch_all_safe", "CATCH_ALL"),
        ("catch_all_not_safe", "CATCH_ALL"),
        ("undeliverable", "INVALID"),
        ("not_found", "UNKNOWN"),
        ("something_new", "UNKNOWN"),
    ] {
        let server = run_server(
            200,
            json!({
                "id": RUN_ID, "status": "terminated",
                "data": [{ "contact_email_address": "a@b.com", "contact_email_address_status": vendor }]
            }),
        )
        .await;
        bettercontact(
            OPEN_GATE,
            &server.uri(),
            &format!(
                r#"
                local emails = c:resolve_email({{ first_name = "A", last_name = "B" }},
                  {{ poll_ms = 1, attempts = 2 }})
                assert.eq(emails[1].verification_status, "{want}")
                "#
            ),
        )
        .await
        .unwrap();
    }
}

/// A 202 while processing carries no `data`, so branching on the HTTP code
/// would read an in-flight run as an empty result.
#[tokio::test]
async fn test_bettercontact_treats_only_terminated_as_finished() {
    let server = run_server(
        202,
        json!({ "id": RUN_ID, "status": "processing", "message": "Processing..." }),
    )
    .await;
    bettercontact(
        OPEN_GATE,
        &server.uri(),
        &format!(
            r#"
            local run = c:result("{RUN_ID}")
            assert.eq(run.status, "processing")
            assert.eq(run.terminated, false)
            assert.eq(#run.people, 0)

            local p, reason = c:find_person({{ first_name = "A", last_name = "B" }},
              {{ poll_ms = 1, attempts = 2 }})
            assert.eq(p, nil)
            assert.eq(reason, "not_terminated")
            "#
        ),
    )
    .await
    .unwrap();
}

/// A declined budget must stop the submission ever reaching the vendor —
/// the difference between a gate and an audit log.
#[tokio::test]
async fn test_bettercontact_declined_budget_never_reaches_the_vendor() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/async"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    bettercontact(
        CLOSED_GATE,
        &server.uri(),
        r#"
        local p, reason = c:find_person({ first_name = "A", last_name = "B" })
        assert.eq(p, nil)
        assert.eq(reason, "over_cap")
        "#,
    )
    .await
    .unwrap();
}

#[tokio::test]
async fn test_bettercontact_distinguishes_auth_credits_and_rate_limit() {
    for (status, want) in [
        (401u16, "rejected the key"),
        (402, "out of credits"),
        (429, "rate limited"),
    ] {
        let server = server_returning("POST", "/async", status).await;
        let err = bettercontact(
            OPEN_GATE,
            &server.uri(),
            r#"c:submit({ { first_name = "A", last_name = "B" } })"#,
        )
        .await
        .unwrap_err();
        assert_says(err, want, &format!("HTTP {status}"));
    }
}

#[tokio::test]
async fn test_bettercontact_refuses_to_build_or_submit_without_the_essentials() {
    for (stmt, want) in [
        (r#"bc.client(nil, { api_key = "k" })"#, "gate is required"),
        (r#"bc.client(gate, { api_key = "" })"#, "api_key required"),
        (
            r#"bc.client(gate, { api_key = "k", base_url = "http://x" }):submit({})"#,
            "at least one person",
        ),
    ] {
        let err = run_lua(&format!(
            "{OPEN_GATE}\nlocal bc = require(\"assay.bettercontact\")\n{stmt}"
        ))
        .await
        .unwrap_err();
        assert_says(err, want, stmt);
    }
}