Create or Update Events from Your CRM
Create an Event from a CRM record (for example Salesforce, HubSpot or Zoho CRM), or update the Event already linked to it.
Example use case
Your CRM has a confirmed show. You want to set up its planning section and Exhibit Hall schedule, then keep the linked Event's name and main dates in sync.
What you'll end up with
A verified link to one ExhibitDay Event and its planning section, plus the saved Exhibit Hall schedule.
Before you start
Have an API key that can read the workspace and perform the setup changes, a stable CRM key, and the complete Exhibit Hall schedule you want to save.
This guide stores your system's ID for each Event in integration_metadata_field_1, one of five API-only text fields on each Event. If another integration already uses field 1, choose a free field (1 to 5) and use it consistently.
Good to know
This works with any CRM that can call a web API or use an automation tool (like Zapier, Make or Pipedream); no special connector is needed.
At a glance
Time to try
About 20 minutes
Effect on your data
Creates and updates
Endpoints
10
The program may create an Event or Task Section, update a linked Event's name or main dates, and replace the Exhibit Hall Dates group. It also writes a private local journal.
How it works
- Each show in your CRM has a stable ID. If the search finds no match, the program creates the Event and saves that ID in integration_metadata_field_1.
- On later runs, it looks up the Event by that ID, so renaming the show keeps the records linked.
- If the CRM name or main dates differ, it updates only those fields after checking the Event's revision.
- It finds or creates the planning Task Section and saves the complete Exhibit Hall schedule if it differs.
- It records save attempts in a private local journal and checks what happened before continuing a stopped run.
Set up the Event
The examples below follow an Event that already exists. Step 3 applies only when the Event search finds no match. Step 8 applies only when the Task Section search finds no match.
Step 1: Confirm the workspace
Read the workspace summary to check where the key will make changes.
curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"id": 98765
}
Check: Confirm id belongs to the workspace you intended to use.
Step 2: Find the linked Event
Search Events by integration_metadata_field_1, the field where your CRM ID is stored, so a name change will not break the link.
curl -X GET "https://api.exhibitday.com/v1/events?filter_by_integration_metadata_field_1=crm%3Aevent%3Aspring-expo-2030&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"records_found": 1,
"total_records": 1,
"has_more": false,
"list_data": [
{
"id": 5001,
"name": "Spring Expo",
"integration_metadata_field_1": "crm:event:spring-expo-2030"
}
]
}
Check: Read every page and compare the saved key exactly. Continue with one distinct match, create with zero, or stop and investigate if there are several.
Step 3: Create the Event if the search found none
Send the CRM values and external key to create the first linked Event.
curl -X POST "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_EVENT_CREATE_KEY" -H "Content-Type: application/json" --data-binary "{\"name\":\"Spring Expo 2030\",\"start_date\":\"2030-01-14\",\"end_date\":\"2030-01-16\",\"integration_metadata_field_1\":\"crm:event:spring-expo-2030\"}"
Example response (shortened)
{
"id": 5001,
"name": "Spring Expo 2030",
"start_date": "2030-01-14",
"end_date": "2030-01-16",
"integration_metadata_field_1": "crm:event:spring-expo-2030"
}
Check: Keep the returned id and confirm the key, name and dates. The program saves the create key in its journal before sending the request.
Step 4: Read the Event and its revision
Read the selected Event by ID so you can check the exact link and compare its current values.
curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"id": 5001,
"name": "Spring Expo",
"start_date": "2030-01-14",
"end_date": "2030-01-15",
"integration_metadata_field_1": "crm:event:spring-expo-2030",
"record_revision": "COPY_EVENT_REVISION_FROM_YOUR_READ"
}
Check: Compare the ID and key. Save record_revision for the next request if an update is needed. The revision below is a placeholder.
Step 5: Update the linked Event if values differ
For an existing linked Event, send only the changed values and the revision from the previous read.
curl -X PATCH "https://api.exhibitday.com/v1/events" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":5001,\"name\":\"Spring Expo 2030\",\"end_date\":\"2030-01-16\",\"expected_revision\":\"COPY_EVENT_REVISION_FROM_YOUR_READ\"}"
Example response (shortened)
{
"status_code": 200,
"status": "OK",
"message": "Event Update Successful. Event properties that were changed: name, end_date",
"record_revision": "NEW_EVENT_REVISION"
}
Check: In this example, name and end_date changed, so start_date is omitted. A successful conditional update returns a new record_revision.
Step 6: Verify the Event before continuing
Read the Event again so the setup only continues when the actual values match the CRM values.
curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"id": 5001,
"name": "Spring Expo 2030",
"start_date": "2030-01-14",
"end_date": "2030-01-16",
"integration_metadata_field_1": "crm:event:spring-expo-2030"
}
Check: Check the ID, integration key, name, start date and end date. The example also checks these values if no update was needed.
Step 7: Find the planning section
Read this Event's Task Sections and look for the exact section name.
curl -X GET "https://api.exhibitday.com/v1/tasks/sections?filter_by_event_id=5001&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"records_found": 1,
"total_records": 1,
"has_more": false,
"list_data": [
{
"id": 6001,
"event_id": 5001,
"name": "Pre-event planning"
}
]
}
Check: Read all matching pages. Use one exact match, create with zero, or stop if there are several.
Step 8: Create the section if none matched
Send the section name with the saved Event ID to add it to this Event.
curl -X POST "https://api.exhibitday.com/v1/tasks/sections" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_SECTION_CREATE_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":5001,\"name\":\"Pre-event planning\"}"
Example response (shortened)
{
"id": 6001,
"event_id": 5001,
"name": "Pre-event planning"
}
Check: Keep the section id and confirm event_id. The section create uses its own saved idempotency key.
Step 9: Verify the section
Read the selected Task Section by ID to confirm its saved details.
curl -X GET "https://api.exhibitday.com/v1/tasks/sections/info?id=6001" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"id": 6001,
"event_id": 5001,
"name": "Pre-event planning"
}
Check: Check the section ID, Event ID and name before continuing.
Step 10: Read the complete Exhibit Hall Dates group
Read date type 1 with its revision so the program can replace that specific group safely.
curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=5001&filter_by_date_type_id=1&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"records_found": 1,
"total_records": 1,
"has_more": false,
"list_data": [
{
"event_id": 5001,
"date_type_id": 1,
"dates": [
{
"date": "2030-01-15",
"start_time": "09:00:00",
"end_time": "15:00:00",
"timezone": "America/New_York",
"description": "Earlier exhibit schedule"
}
],
"record_revision": "COPY_DATES_REVISION_FROM_YOUR_READ"
}
]
}
Check: Confirm the Event and date type in the one returned group. Use that group's record_revision for the Dates update. The revision below is a placeholder.
Step 11: Save the complete Exhibit Hall schedule
Replace the group with every date and time you want to keep, using the Dates revision.
curl -X PATCH "https://api.exhibitday.com/v1/events/dates" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"event_id\":5001,\"date_type_id\":1,\"dates\":[{\"date\":\"2030-01-15\",\"start_time\":\"09:00:00\",\"end_time\":\"17:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Exhibit hours\"},{\"date\":\"2030-01-16\",\"start_time\":\"09:00:00\",\"end_time\":\"16:00:00\",\"timezone\":\"America/New_York\",\"description\":\"Final exhibit day\"}],\"expected_revision\":\"COPY_DATES_REVISION_FROM_YOUR_READ\"}"
Example response (shortened)
{
"status_code": 200,
"status": "OK",
"message": "Event Dates updated.",
"record_revision": "NEW_DATES_REVISION"
}
Check: Look for the saved record_revision. Dates you leave out are removed from this group, so include every date you want to keep.
Step 12: Verify the saved schedule
Read the group again to check that the complete saved schedule matches what you sent.
curl -X GET "https://api.exhibitday.com/v1/events/dates?event_id=5001&filter_by_date_type_id=1" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"records_found": 1,
"total_records": 1,
"has_more": false,
"list_data": [
{
"event_id": 5001,
"date_type_id": 1,
"dates": [
{
"date": "2030-01-15",
"start_time": "09:00:00",
"end_time": "17:00:00",
"timezone": "America/New_York",
"description": "Exhibit hours"
},
{
"date": "2030-01-16",
"start_time": "09:00:00",
"end_time": "16:00:00",
"timezone": "America/New_York",
"description": "Final exhibit day"
}
]
}
]
}
Check: Compare each date, local time, time-zone label and description in the order the API returns them.
Step 13: Confirm the final Event setup
Read the Event again to verify its CRM link and planning section after the separate saves.
curl -X GET "https://api.exhibitday.com/v1/events/info?id=5001" -H "Authorization: Bearer YOUR_API_KEY"
Example response (shortened)
{
"id": 5001,
"name": "Spring Expo 2030",
"start_date": "2030-01-14",
"end_date": "2030-01-16",
"integration_metadata_field_1": "crm:event:spring-expo-2030",
"task_sections": [
{
"id": 6001,
"name": "Pre-event planning",
"display_rank": 0
},
{
"id": 6002,
"name": "Onsite follow-up",
"display_rank": 1
}
]
}
Check: Confirm the ID, key, name and dates, and find the saved section ID in task_sections.
Try it
Before running the example
| Variable | What to put in it | Required? |
|---|---|---|
EXHIBITDAY_API_KEY | Your workspace API key. | Yes |
EXHIBITDAY_EXTERNAL_EVENT_KEY | A stable CRM key, up to 3,000 UTF-16 code units. Leave no whitespace at either end. | Yes |
EXHIBITDAY_EVENT_NAME | The Event name, up to 500 UTF-16 code units. Use plain, single-line text with no surrounding whitespace. | Yes |
EXHIBITDAY_START_DATE | The main start date in YYYY-MM-DD format. | Yes |
EXHIBITDAY_END_DATE | The main end date in YYYY-MM-DD format, on or after the start date. | Yes |
EXHIBITDAY_EXHIBIT_DATES_JSON | The entire desired Exhibit Hall Dates array. Use all five fields per entry, including normalized times such as 09:00:00, in the order returned by the API. | Yes |
EXHIBITDAY_JOURNAL | A private local journal path for this setup. | Yes |
EXHIBITDAY_JOB_ID | A stable ID for this setup. Keep it for a resume. | Yes |
EXHIBITDAY_TASK_SECTION_NAME | The exact name to find or create. The default is Pre-event planning. | No |
EXHIBITDAY_PAGE_SIZE | The page size for the searches. The default is 100. | No |
EXHIBITDAY_JOB_MODE | Use new for a new job or resume for the existing journal. The default is resume. | No |
Bash
export EXHIBITDAY_API_KEY='YOUR_API_KEY'
export EXHIBITDAY_EXTERNAL_EVENT_KEY='crm:event:spring-expo-2030'
export EXHIBITDAY_EVENT_NAME='Spring Expo 2030'
export EXHIBITDAY_START_DATE='2030-01-14'
export EXHIBITDAY_END_DATE='2030-01-16'
export EXHIBITDAY_EXHIBIT_DATES_JSON='[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]'
PowerShell
$env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY'
$env:EXHIBITDAY_EXTERNAL_EVENT_KEY = 'crm:event:spring-expo-2030'
$env:EXHIBITDAY_EVENT_NAME = 'Spring Expo 2030'
$env:EXHIBITDAY_START_DATE = '2030-01-14'
$env:EXHIBITDAY_END_DATE = '2030-01-16'
$env:EXHIBITDAY_EXHIBIT_DATES_JSON = '[{"date":"2030-01-15","start_time":"09:00:00","end_time":"17:00:00","timezone":"America/New_York","description":"Exhibit hours"},{"date":"2030-01-16","start_time":"09:00:00","end_time":"16:00:00","timezone":"America/New_York","description":"Final exhibit day"}]'
Set a private journal path and a stable job ID. For the first run, set EXHIBITDAY_JOB_MODE=new. Then copy and run the complete example in your language.
Complete example program
#!/usr/bin/env bash
# Requires Bash, curl and Python3. No API key is written into the program.
python3 - <<'EXHIBITDAY_PY'
# Python 3; standard library only. Set EXHIBITDAY_API_KEY before running.
import http.client
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
BASE = "https://api.exhibitday.com/v1"
SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}")
API_KEY = os.environ["EXHIBITDAY_API_KEY"]
if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY):
raise RuntimeError("Use the API key as one ASCII header value without control characters")
if not API_KEY.strip():
raise RuntimeError("Set EXHIBITDAY_API_KEY")
def decode_json(text):
if SPEC["preserveNumbers"]:
# Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact.
text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?',
lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text)
return json.loads(text)
from pathlib import Path
# This terminal version uses curl for HTTP and Python's standard library for JSON/CSV.
import subprocess
import tempfile
def transport(method, url, headers, data):
with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory:
folder = Path(directory)
# curl may leave no output file for a valid bodyless304 response.
(folder / "body").write_bytes(b"")
command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url,
"--max-time", "30", "--dump-header", str(folder / "headers"),
"--output", str(folder / "body"), "--write-out", "%{http_code}"]
for name, value in headers.items():
command += ["--header", name + ": " + value]
if data is not None:
(folder / "request").write_bytes(data)
command += ["--data-binary", "@" + str(folder / "request")]
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode:
raise urllib.error.URLError(result.stderr.strip())
response_headers = {}
blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n")
for line in blocks[-1].splitlines()[1:]:
name, separator, value = line.partition(":")
if separator:
response_headers[name] = value.strip()
return int(result.stdout), (folder / "body").read_bytes(), response_headers
class ApiError(RuntimeError):
"""An API error response. Branch on error_code (and status), never on the message text.
uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied."""
def __init__(self, status, body, uncertain=False):
self.status = status
self.uncertain = uncertain
self.error_code = body.get("error_code") if isinstance(body, dict) else None
super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})"
if isinstance(body, dict) else "HTTP " + str(status) if status else "No response")
def call(name, params=None, body=None, key=None):
route = SPEC["requests"][name]
headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"}
if route["method"] == "POST":
if not key: raise RuntimeError("Persist a logical create key before sending POST")
headers["Idempotency-Key"] = key
data = None if body is None else json.dumps(body).encode("utf-8")
if data is not None:
headers["Content-Type"] = "application/json"
query = urllib.parse.urlencode(params or {})
url = BASE + route["path"] + ("?" + query if query else "")
# Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
# server error is never resent blindly: it may already have been applied, so the caller reads the record first.
resend = route["method"] == "GET"
for attempt in range(5):
try:
status, raw, response_headers = transport(route["method"], url, headers, data)
except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException):
if not resend:
raise ApiError(0, None, uncertain=True)
if attempt == 4:
raise
time.sleep(2 ** attempt)
continue
response_headers = {k.lower(): v for k, v in response_headers.items()}
result = None
if status != 304 and raw:
try:
result = decode_json(raw.decode("utf-8"))
except (ValueError, UnicodeError):
if status < 400:
raise RuntimeError("Expected a JSON success response")
if status >= 500 and not resend:
raise ApiError(status, result, uncertain=True)
retry = resend and (status == 429 or status >= 500)
if retry:
if attempt == 4:
raise RuntimeError("Retry limit reached; check the request outcome before starting a new create")
delay = response_headers.get("retry-after", str(2 ** attempt))
time.sleep(max(0, float(delay)))
continue
if status >= 400:
raise ApiError(status, result)
return {"status": status, "body": result, "headers": response_headers, "raw": raw}
raise RuntimeError("Retry limit reached")
def add_offset(offset, received):
result = int(offset) + received
if received <= 0 or result > 2147483647: raise RuntimeError("Cannot advance this int32 offset; reconcile the query")
return str(result)
def both(left,right):
return left and right
def items(value):
if not isinstance(value, list): raise RuntimeError("Expected a JSON array")
return value
def count(value):
return len(items(value))
def deep_equal(left,right):
if type(left) is not type(right): return False
if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left)
if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right))
return left==right
def either(left, right):
if not isinstance(left, bool) or not isinstance(right, bool): raise RuntimeError("Expected Boolean criteria")
return left or right
def equal(left, right):
return type(left) is type(right) and left == right
def field(value, name):
if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name)
return value[name]
def is_empty(value):
return count(value) == 0
def is_present(value):
return value is not None and value != ""
"""Strict private client journal reference; no transport or application dependency."""
from pathlib import Path
import hashlib
import os
import re
import secrets
from urllib.parse import urlsplit
PREAMBLE=b'EXHIBITDAY-GUIDE-JOURNAL 1\n'
class JournalRefusal(RuntimeError):
pass
def utf8(value):
if not isinstance(value,str):raise JournalRefusal('Journal fields are exact strings')
return value.encode('utf-8',errors='strict')
def strings(values):
raw=bytearray()
for value in values:
item=utf8(value);raw.extend(str(len(item)).encode('ascii'));raw.extend(b':');raw.extend(item)
return bytes(raw)
def read_strings(raw):
values=[];offset=0
while offset<len(raw):
end=raw.find(b':',offset)
if end<0:raise JournalRefusal('Incomplete journal string length')
length=raw[offset:end]
if not re.fullmatch(b'0|[1-9][0-9]*',length):raise JournalRefusal('Noncanonical journal string length')
size=int(length);offset=end+1
if size>len(raw)-offset:raise JournalRefusal('Incomplete journal string')
values.append(raw[offset:offset+size].decode('utf-8',errors='strict'));offset+=size
return values
def digest(raw):return hashlib.sha256(raw).hexdigest().upper()
def fingerprint(pairs):
values=[]
for name,value in sorted(pairs.items()):
if not re.fullmatch('[A-Za-z0-9_.-]+',name):raise JournalRefusal('Fingerprint field names must be explicit ASCII identifiers')
if name.lower() in ('api_key','exhibitday_api_key'):raise JournalRefusal('Never fingerprint the API key')
values.extend((name,value))
return digest(strings(values))
def frame(values):
raw=strings(values)
return str(len(raw)).encode('ascii')+b' '+digest(raw).encode('ascii')+b'\n'+raw+b'\n'
def decode(raw):
if not raw.startswith(PREAMBLE):raise JournalRefusal('Unknown or incomplete journal version')
offset=len(PREAMBLE);records=[]
while offset<len(raw):
end=raw.find(b'\n',offset)
if end<0:raise JournalRefusal('Incomplete journal frame header; reconcile before retry')
match=re.fullmatch(b'(0|[1-9][0-9]*) ([0-9A-F]{64})',raw[offset:end])
if match is None:raise JournalRefusal('Invalid journal frame header')
size=int(match[1]);offset=end+1
if size>=len(raw)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry')
payload=raw[offset:offset+size];offset+=size
if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry')
records.append(read_strings(payload));offset+=1
return records
class Journal:
def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"):
self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={};self.adopted_values={};self.order=[]
address=urlsplit(base)
if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug')
if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint')
if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job")
self.allowed={};manifest=[]
for step,method,route in writes:
if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest')
self.allowed[step]=(method,route);self.order.append(step);manifest.extend((step,method,route))
if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal')
self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))]
strings(self.header)
try:
self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True
except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock')
try:
self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd)
if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write')
os.fsync(self.fd)
if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file')
if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job")
if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job")
if mode=="new":
with open(self.path,'xb',buffering=0)as target:
target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno())
records=decode(self.path.read_bytes())
if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs')
for record in records[1:]:self.apply(record)
if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry')
except BaseException:
self.close();raise
def apply(self,record):
if not record:raise JournalRefusal('Empty journal record')
if record[0]=='I':
if len(record)!=6:raise JournalRefusal('Invalid intent shape')
_,step,method,path,request_fingerprint,key=record
if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or step in self.adopted_values or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent')
if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key')
self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key}
elif record[0]=='A':
if len(record)<3:raise JournalRefusal('Invalid ACK shape')
_,step,count,*pairs=record
if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent')
names=pairs[::2]
if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers')
self.saved_values[step]=dict(zip(names,pairs[1::2]))
elif record[0]=='S':
if len(record)<6:raise JournalRefusal('Invalid read-adoption shape')
_,step,method,path,read_fingerprint,count,*pairs=record
completed=set(self.saved_values)|set(self.adopted_values)
if len(completed)>=len(self.order) or completed!=set(self.order[:len(completed)]) or step!=self.order[len(completed)] or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Adopt only the exact next setup action without any pending intent')
target=self.allowed.get(step)
expected='/v1/events/info'if (target==('POST','/v1/events') or step=='update_event' and target==('PATCH','/v1/events'))else '/v1/tasks/sections/info'if target==('POST','/v1/tasks/sections')else None
if method!='GET' or expected is None or path!=expected:raise JournalRefusal('Adoption requires the exact source-bound single Event or section read')
if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count):raise JournalRefusal('Invalid read-adoption field count')
names=pairs[::2];fields=['id','integration_metadata_field_1']if expected=='/v1/events/info'else ['event_id','id','name']
if names!=fields:raise JournalRefusal('Read-adoption fields must match the exact source tuple')
saved=dict(zip(names,pairs[1::2]))
for name in ('id','event_id'):
if name in saved and (not re.fullmatch('[1-9][0-9]*',saved[name])or int(saved[name])>9223372036854775807):raise JournalRefusal('Read-adoption IDs must be exact positive Int64 strings')
if any(saved[name]==''for name in fields if name not in ('id','event_id'))or read_fingerprint!=fingerprint(saved):raise JournalRefusal('Read-adoption material must be complete and fingerprint-bound')
self.adopted_values[step]=saved
else:raise JournalRefusal('Unknown journal transition')
def append(self,record):
# The reader commits state only after complete length/digest recognition.
# A torn append is retained and refused, never silently truncated.
self.require_active();raw=frame(record)
try:
with open(self.path,'ab',buffering=0)as target:
view=memoryview(raw)
while view:
written=target.write(view)
if not written:raise OSError('Journal write did not advance')
view=view[written:]
os.fsync(target.fileno())
except BaseException:
self.tainted=True;raise
def require_active(self):
if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation')
current=self.lock.stat(follow_symlinks=False)
if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it')
def acknowledged(self,step):
self.require_active();return step in self.saved_values
def saved(self,step):
self.require_active()
if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step')
return dict(self.saved_values[step])
def completed(self,step):
self.require_active();return step in self.saved_values or step in self.adopted_values
def recorded(self,step):
self.require_active()
if step in self.saved_values:return dict(self.saved_values[step])
if step in self.adopted_values:return dict(self.adopted_values[step])
raise JournalRefusal('No completed write or read-adoption exists')
def adopted(self,step):
self.require_active();return step in self.adopted_values
def adopt(self,step,source_method,source_path,saved):
self.require_active()
record=['S',step,source_method,source_path,fingerprint(saved),str(len(saved))]
for name,value in sorted(saved.items()):record.extend((name,value))
old={name:dict(value)for name,value in self.adopted_values.items()}
try:self.apply(record);strings(record)
finally:self.adopted_values=old
self.append(record);self.apply(record)
def begin(self,step,method,path,request_fingerprint):
self.require_active()
if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent')
key=secrets.token_hex(16)if method=='POST'else''
record=['I',step,method,path,request_fingerprint,key]
# Validate on an isolated state before touching the file.
old=dict(self.intents)
try:self.apply(record)
finally:self.intents=old
self.append(record);self.apply(record)
return dict(self.intents[step])
def acknowledge(self,step,saved):
self.require_active()
record=['A',step,str(len(saved))]
for name,value in sorted(saved.items()):record.extend((name,value))
old={name:dict(value)for name,value in self.saved_values.items()}
try:self.apply(record);strings(record)
finally:self.saved_values=old
self.append(record);self.apply(record)
def close(self):
if self.owned:
if self.tainted:
os.close(self.fd);self.fd=None;self.owned=False
return # Retain this lock after failed journal IO; manual reconciliation is required.
try:self.require_active()
except BaseException:
os.close(self.fd);self.fd=None;self.owned=False;raise
os.close(self.fd);self.fd=None;self.owned=False
self.lock.unlink()
def __enter__(self):return self
def __exit__(self,*args):self.close()
def journal_values(value):
if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()):
raise JournalRefusal('Saved/fingerprint values must be exact string fields')
return dict(value)
def journal_acknowledge(job, step, saved):
job.acknowledge(step,journal_values(saved))
def journal_acknowledged(job, step):
return job.acknowledged(step)
def journal_adopt(job,step,method,path,saved):job.adopt(step,method,path,journal_values(saved))
def journal_begin(job, step, method, path, request_fingerprint):
return job.begin(step,method,path,request_fingerprint)
def journal_completed(job,step):return job.completed(step)
def journal_fingerprint(value):
return fingerprint(journal_values(value))
def journal_recorded(job,step):return job.recorded(step)
def not_value(value):
if not isinstance(value, bool): raise RuntimeError("Expected a Boolean")
return not value
def open_journal(path, base, workspace, slug, job, input_fingerprint, writes, mode):
return Journal(path,base,workspace,slug,job,input_fingerprint,writes,mode)
def optional(name, fallback):
value = os.environ.get(name)
return fallback if value is None or value == "" else value
def page_size(value):
if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32")
return value
def parse_json(value):
import math
def pairs(values):
result={}
for key,item in values:
if key in result:raise ValueError('Duplicate JSON input property')
result[key]=item
return result
def number(value):
result=float(value)
if not math.isfinite(result):raise ValueError('Use finite JSON numbers')
return result
def invalid(value):raise ValueError('Use standard JSON values')
return json.loads(value,object_pairs_hook=pairs,parse_float=number,parse_constant=invalid)
def positive_id(value):
if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID")
return value
def print_value(value):
print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False))
def require_condition(value, message):
if value is not True: raise RuntimeError(message)
def required(name):
value = os.environ.get(name)
if value is None or not value.strip(): raise RuntimeError("Set " + name)
return value
def response_status(value):
return str(value["status"])
def single(value):
rows=items(value)
if len(rows)!=1: raise RuntimeError('Expected exactly one selected record')
return rows[0]
def text(value):
if value is None: return ""
if isinstance(value, str): return value
if isinstance(value, bool): return "true" if value else "false"
if isinstance(value, int): return str(value)
raise RuntimeError("Expected a scalar response value")
def validate_crm_event_inputs(key, name, start, end):
from datetime import date
spaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000'
for value, label, limit in ((name, 'EXHIBITDAY_EVENT_NAME', 500), (key, 'EXHIBITDAY_EXTERNAL_EVENT_KEY', 3000)):
utf8(value)
if not value or value != value.strip(spaces):
raise JournalRefusal('Remove whitespace at the start or end of ' + label)
if len(value.encode('utf-16-le')) // 2 > limit:
raise JournalRefusal(label + ' exceeds ' + str(limit) + ' UTF-16 code units')
if any(ch in name for ch in '<>\r\n') or name.lower() == 'null':
raise JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null')
for value, label in ((start, 'EXHIBITDAY_START_DATE'), (end, 'EXHIBITDAY_END_DATE')):
try:
valid = re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value).year >= 1753
except ValueError:
valid = False
if not valid:
raise JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01')
if end < start:
raise JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE')
def main():
external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY")
desired_event_name = required("EXHIBITDAY_EVENT_NAME")
desired_start_date = required("EXHIBITDAY_START_DATE")
desired_end_date = required("EXHIBITDAY_END_DATE")
desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON")
desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning")
setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100"))
desired_setup_dates = items(parse_json(desired_dates_json))
validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date)
journal_path = required("EXHIBITDAY_JOURNAL")
stable_job_id = required("EXHIBITDAY_JOB_ID")
job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
setup_workspace_response = call("workspace_binding", {}, None, None)
require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_workspace = setup_workspace_response["body"]
owned_workspace_id = positive_id(text(field(setup_workspace, "id")))
setup_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json})
setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, [["create_event", "POST", "/v1/events"], ["update_event", "PATCH", "/v1/events"], ["create_section", "POST", "/v1/tasks/sections"], ["save_dates", "PATCH", "/v1/events/dates"]], job_mode)
try:
setup_event_id = ""
setup_section_id = ""
recorded_section_name = desired_section_name
if journal_completed(setup_job, "create_event"):
recorded_event = journal_recorded(setup_job, "create_event")
setup_event_id = positive_id(text(field(recorded_event, "id")))
require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.")
else:
event_search_offset = "0"
event_search_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size}
while True:
event_search_query["$offset"] = event_search_offset
event_search_response = call("find_existing", event_search_query, None, None)
require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
event_search_page = event_search_response["body"]
event_search_rows = items(field(event_search_page, "list_data"))
require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.")
require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.")
require_condition(either(equal(field(event_search_page, "has_more"), True), equal(field(event_search_page, "has_more"), False)), "Expected a Boolean has_more value.")
for event_search_row in items(event_search_rows):
if equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key):
event_search_candidate_id = positive_id(text(field(event_search_row, "id")))
if is_present(setup_event_id):
require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.")
setup_event_id = event_search_candidate_id
if equal(field(event_search_page, "has_more"), False):
break
require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.")
event_search_offset = add_offset(event_search_offset, count(event_search_rows))
if not_value(is_present(setup_event_id)):
event_write_fingerprint = journal_fingerprint({"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key})
event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint)
event_create_response = call("create_event", {}, {"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key")))
require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
created_event = event_create_response["body"]
setup_event_id = positive_id(text(field(created_event, "id")))
require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.")
require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.")
journal_acknowledge(setup_job, "create_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key})
event_confirmation_response = call("confirm_event", {"id": setup_event_id, "$include_record_revision": "true"}, None, None)
require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
confirmed_setup_event = event_confirmation_response["body"]
require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.")
if not_value(journal_completed(setup_job, "create_event")):
journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", {"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))})
setup_event_revision = text(field(confirmed_setup_event, "record_revision"))
require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.")
require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.")
if journal_completed(setup_job, "update_event"):
recorded_event_update = journal_recorded(setup_job, "update_event")
require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.")
require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.")
else:
if both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)):
journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", {"id": setup_event_id, "integration_metadata_field_1": external_event_key})
else:
require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.")
event_update_body = {"id": setup_event_id, "expected_revision": setup_event_revision}
if not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name)):
event_update_body["name"] = desired_event_name
if not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)):
event_update_body["start_date"] = desired_start_date
if not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)):
event_update_body["end_date"] = desired_end_date
event_update_fingerprint = journal_fingerprint(event_update_body)
journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint)
event_update_response = call("update_event", {}, event_update_body, None)
require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
event_update_ack = event_update_response["body"]
event_updated_revision = text(field(event_update_ack, "record_revision"))
require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.")
journal_acknowledge(setup_job, "update_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision})
event_update_verify_response = call("verify_event_update", {"id": setup_event_id}, None, None)
require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
verified_setup_event = event_update_verify_response["body"]
require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.")
if journal_completed(setup_job, "create_section"):
recorded_section = journal_recorded(setup_job, "create_section")
setup_section_id = positive_id(text(field(recorded_section, "id")))
require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.")
recorded_section_name = text(field(recorded_section, "name"))
else:
section_search_offset = "0"
section_search_query = {"filter_by_event_id": setup_event_id, "$limit": setup_page_size}
while True:
section_search_query["$offset"] = section_search_offset
section_search_response = call("find_section", section_search_query, None, None)
require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
section_search_page = section_search_response["body"]
section_search_rows = items(field(section_search_page, "list_data"))
require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.")
require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.")
require_condition(either(equal(field(section_search_page, "has_more"), True), equal(field(section_search_page, "has_more"), False)), "Expected a Boolean has_more value.")
for section_search_row in items(section_search_rows):
require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.")
if equal(text(field(section_search_row, "name")), desired_section_name):
section_search_candidate_id = positive_id(text(field(section_search_row, "id")))
if is_present(setup_section_id):
require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.")
setup_section_id = section_search_candidate_id
if equal(field(section_search_page, "has_more"), False):
break
require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.")
section_search_offset = add_offset(section_search_offset, count(section_search_rows))
if not_value(is_present(setup_section_id)):
section_write_fingerprint = journal_fingerprint({"event_id": setup_event_id, "name": desired_section_name})
section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint)
section_create_response = call("create_section", {}, {"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key")))
require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
created_section = section_create_response["body"]
setup_section_id = positive_id(text(field(created_section, "id")))
require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.")
recorded_section_name = text(field(created_section, "name"))
require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.")
journal_acknowledge(setup_job, "create_section", {"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name})
section_confirmation_response = call("confirm_section", {"id": setup_section_id}, None, None)
require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
confirmed_setup_section = section_confirmation_response["body"]
require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.")
if not_value(journal_completed(setup_job, "create_section")):
journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", {"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))})
setup_dates_response = call("read_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, None, None)
require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_page = setup_dates_response["body"]
require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.")
setup_dates_group = single(field(setup_dates_page, "list_data"))
require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.")
setup_dates_revision = text(field(setup_dates_group, "record_revision"))
require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.")
if journal_completed(setup_job, "save_dates"):
recorded_dates = journal_recorded(setup_job, "save_dates")
require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.")
else:
setup_dates_fingerprint = journal_fingerprint({"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision})
journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint)
setup_dates_save_response = call("save_dates", {}, {"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, None)
require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_ack = setup_dates_save_response["body"]
setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision"))
require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.")
journal_acknowledge(setup_job, "save_dates", {"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision})
setup_dates_verify_response = call("verify_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1"}, None, None)
require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_verify_page = setup_dates_verify_response["body"]
require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.")
setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data"))
require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.")
require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.")
setup_event_readback_response = call("event_readback", {"id": setup_event_id}, None, None)
require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_event_readback = setup_event_readback_response["body"]
require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.")
require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.")
planning_section_present = False
for setup_event_section in items(items(field(setup_event_readback, "task_sections"))):
if equal(text(field(setup_event_section, "id")), setup_section_id):
planning_section_present = True
require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.")
print_value({"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"})
finally:
setup_job.close()
if __name__ == "__main__":
main()
EXHIBITDAY_PY
// Server-side Node.js with fetch; built-in modules only. Set EXHIBITDAY_API_KEY.
const BASE = "https://api.exhibitday.com/v1";
const SPEC = JSON.parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}");
const API_KEY = process.env.EXHIBITDAY_API_KEY;
if (!API_KEY || !API_KEY.trim()) throw new Error("Set EXHIBITDAY_API_KEY");
if (/[^\x20-\x7e]/.test(API_KEY)) throw new Error("Use the API key as one ASCII header value without control characters");
const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
function decodeJson(text) {
if (SPEC.preserveNumbers) {
// Keep raw JSON number tokens exact for CSV; quoted JSON strings remain unchanged.
text = text.replace(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,
token => token.startsWith('"') ? token : JSON.stringify(token));
}
return JSON.parse(text);
}
// An API error response. Branch on errorCode (and status), never on the message text.
// uncertain is true when a PATCH or DELETE got no response or a server error: it may or may not have been applied.
class ApiError extends Error {
constructor(status, result, uncertain = false) {
super(result ? JSON.stringify({ error_code: result.error_code, errors: result.errors,
error_params: result.error_params, request_id: result.request_id }) : status ? "HTTP " + status : "No response");
this.status = status;
this.errorCode = result ? result.error_code : undefined;
this.uncertain = uncertain;
}
}
async function call(name, params = {}, body = null, key = null) {
const route = SPEC.requests[name];
const headers = { Authorization: "Bearer " + API_KEY, Accept: "application/json" };
if (route.method === "POST") {
if (!key) throw new Error("Persist a logical create key before sending POST");
headers["Idempotency-Key"] = key;
}
const data = body === null ? undefined : JSON.stringify(body);
if (data !== undefined) headers["Content-Type"] = "application/json";
const query = new URLSearchParams(params).toString();
const url = BASE + route.path + (query ? "?" + query : "");
// Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
// server error is never resent blindly: it may already have been applied, so the caller reads the record first.
const resend = route.method === "GET";
for (let attempt = 0; attempt < 5; attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
let response, raw;
try {
response = await fetch(url, { method: route.method, headers, body: data, signal: controller.signal, redirect: "error" });
raw = await response.text();
} catch (error) {
if (!resend) throw new ApiError(0, null, true);
if (attempt === 4) throw error;
await sleep(1000 * 2 ** attempt);
continue;
} finally { clearTimeout(timer); }
const resultHeaders = {};
response.headers.forEach((value, name) => { resultHeaders[name.toLowerCase()] = value; });
let result = null;
if (response.status !== 304 && raw) {
try { result = decodeJson(raw); }
catch (error) { if (response.status < 400) throw new Error("Expected a JSON success response"); }
}
if (response.status >= 500 && !resend) throw new ApiError(response.status, result, true);
const retry = resend && (response.status === 429 || response.status >= 500);
if (retry) {
if (attempt === 4) throw new Error("Retry limit reached; check the outcome before starting a new create");
const requested = Number(resultHeaders["retry-after"]);
await sleep(1000 * (Number.isFinite(requested) && requested >= 0 ? requested : 2 ** attempt));
continue;
}
if (response.status >= 400) throw new ApiError(response.status, result);
return { status: response.status, body: result, headers: resultHeaders, raw };
}
throw new Error("Retry limit reached");
}
function add_offset(offset, received) { const result = BigInt(offset) + received; if (received <= 0n || result > 2147483647n) throw new Error("Cannot advance this int32 offset; reconcile the query"); return result.toString(); }
function both(left,right) { return left && right; }
function items(value) { if (!Array.isArray(value)) throw new Error("Expected a JSON array"); return value; }
function count(value) { return BigInt(items(value).length); }
function deep_equal(left,right) {
if(left===null||right===null)return left===right;
if(typeof left!==typeof right||Array.isArray(left)!==Array.isArray(right))return false;
if(typeof left!=='object')return left===right;
const a=Object.keys(left).sort(),b=Object.keys(right).sort();return a.length===b.length&&a.every((k,i)=>k===b[i]&&deep_equal(left[k],right[k]));
}
function either(left, right) { if (typeof left !== "boolean" || typeof right !== "boolean") throw new Error("Expected Boolean criteria"); return left || right; }
function equal(left, right) { return typeof left === typeof right && left === right; }
function field(value, name) { if (!value || Array.isArray(value) || typeof value !== "object" || !Object.hasOwn(value, name)) throw new Error("Missing response field: " + name); return value[name]; }
function is_empty(value) { return count(value) === 0n; }
function is_present(value) { return value !== null && value !== undefined && value !== ""; }
'use strict';
// Private client restart state. No HTTP or application dependency.
const fs = require('node:fs');
const crypto = require('node:crypto');
const PREAMBLE = Buffer.from('EXHIBITDAY-GUIDE-JOURNAL 1\n', 'ascii');
class JournalRefusal extends Error {}
function ascii(raw) {
if (raw.some(value => value > 127)) throw new JournalRefusal('Journal framing must be canonical ASCII');
return raw.toString('ascii');
}
function utf8(value) {
if (typeof value !== 'string') throw new JournalRefusal('Journal fields are exact strings');
for (const unit of value) if (unit.length === 1 && unit.charCodeAt(0) >= 0xd800 && unit.charCodeAt(0) <= 0xdfff)
throw new JournalRefusal('Invalid Unicode journal field');
return Buffer.from(value, 'utf8');
}
function strings(values) {
const parts = [];
for (const value of values) { const raw = utf8(value); parts.push(Buffer.from(String(raw.length) + ':', 'ascii'), raw); }
return Buffer.concat(parts);
}
function readStrings(raw) {
const values = []; let offset = 0;
while (offset < raw.length) {
const end = raw.indexOf(58, offset);
if (end < 0) throw new JournalRefusal('Incomplete journal string length');
const length = ascii(raw.subarray(offset, end));
if (!/^(0|[1-9][0-9]*)$/.test(length)) throw new JournalRefusal('Noncanonical journal string length');
const size = BigInt(length); offset = end + 1;
if (size > BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal string');
const count = Number(size);
values.push(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw.subarray(offset, offset + count))); offset += count;
}
return values;
}
function digest(raw) { return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase(); }
function fingerprint(pairs) {
const values = [];
for (const name of Object.keys(pairs).sort()) {
if (!/^[A-Za-z0-9_.-]+$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name.toLowerCase()))
throw new JournalRefusal('Use explicit secret-free fingerprint field names');
values.push(name, pairs[name]);
}
return digest(strings(values));
}
function frame(values) {
const raw = strings(values);
return Buffer.concat([Buffer.from(String(raw.length) + ' ' + digest(raw) + '\n', 'ascii'), raw, Buffer.from('\n')]);
}
function decode(raw) {
if (!raw.subarray(0, PREAMBLE.length).equals(PREAMBLE)) throw new JournalRefusal('Unknown or incomplete journal version');
let offset = PREAMBLE.length; const records = [];
while (offset < raw.length) {
const end = raw.indexOf(10, offset);
if (end < 0) throw new JournalRefusal('Incomplete journal frame header; reconcile before retry');
const match = /^(0|[1-9][0-9]*) ([0-9A-F]{64})$/.exec(ascii(raw.subarray(offset, end)));
if (!match) throw new JournalRefusal('Invalid journal frame header');
const size = BigInt(match[1]); offset = end + 1;
if (size >= BigInt(raw.length - offset)) throw new JournalRefusal('Incomplete journal frame; reconcile before retry');
const count = Number(size), payload = raw.subarray(offset, offset + count); offset += count;
if (raw[offset] !== 10 || digest(payload) !== match[2]) throw new JournalRefusal('Journal integrity check failed; reconcile before retry');
records.push(readStrings(payload)); offset++;
}
return records;
}
function writeAll(fd, raw) {
let offset = 0;
while (offset < raw.length) { const count = fs.writeSync(fd, raw, offset, raw.length - offset); if (!count) throw new Error('Journal write did not advance'); offset += count; }
}
function same(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); }
class Journal {
constructor(path, base, workspace, slug, job, inputFingerprint, writes, mode = 'resume') {
this.path = path; this.lock = path + '.lock'; this.fd = null; this.owned = false; this.identity = null; this.tainted = false;
this.intents = new Map(); this.savedValues = new Map(); this.adoptedValues = new Map(); this.allowed = new Map();
if (!['new', 'resume'].includes(mode)) throw new JournalRefusal('Choose new or resume for this local job');
const address = new URL(base);
if (!['https:', 'http:'].includes(address.protocol) || !address.hostname || address.username || address.password || address.search || address.hash || !/^[a-z][a-z0-9-]*$/.test(slug))
throw new JournalRefusal('Use the actual API base and closed guide slug');
if (!job.trim() || !/^[1-9][0-9]*$/.test(workspace) || !/^[0-9A-F]{64}$/.test(inputFingerprint))
throw new JournalRefusal('Use an actual workspace, stable explicit job ID and exact input fingerprint');
const manifest = [];
for (const [step, method, route] of writes) {
if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.allowed.has(step) || !['POST', 'PATCH', 'DELETE'].includes(method) || !/^\/v1\/[A-Za-z0-9_/-]+$/.test(route) || route.includes('//'))
throw new JournalRefusal('Use a closed unique write manifest');
this.allowed.set(step, [method, route]); manifest.push(step, method, route);
}
if (!this.allowed.size) throw new JournalRefusal('Only write workflows need a restart journal');
this.header = ['H', '1', base, workspace, slug, job, inputFingerprint, digest(strings(manifest))]; strings(this.header);
try { this.fd = fs.openSync(this.lock, 'wx', 0o600); this.owned = true; }
catch (error) { if (error.code === 'EEXIST') throw new JournalRefusal('This journal is locked; do not overlap jobs or steal a stale lock'); throw error; }
try {
this.owner = crypto.randomBytes(16).toString('hex'); this.identity = fs.fstatSync(this.fd, { bigint: true });
writeAll(this.fd, Buffer.from(this.owner, 'ascii')); fs.fsyncSync(this.fd);
let exists = true;
try { if (fs.lstatSync(path).isSymbolicLink()) throw new JournalRefusal('Choose a private regular journal file'); }
catch (error) { if (error.code === 'ENOENT') exists = false; else throw error; }
if (mode === 'resume' && !exists) throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');
if (mode === 'new' && exists) throw new JournalRefusal('Journal already exists; use resume for the same logical job');
if (mode === 'new') {
const target = fs.openSync(path, 'wx', 0o600);
try { writeAll(target, Buffer.concat([PREAMBLE, frame(this.header)])); fs.fsyncSync(target); } finally { fs.closeSync(target); }
}
const records = decode(fs.readFileSync(path));
if (!records.length || !same(records[0], this.header)) throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');
for (const record of records.slice(1)) this.apply(record);
if ([...this.intents.keys()].some(step => !this.savedValues.has(step))) throw new JournalRefusal('Saved before-send intent lacks ACK; stop and reconcile before retry');
} catch (error) { this.close(); throw error; }
}
apply(record) {
if (record[0] === 'I') {
if (record.length !== 6) throw new JournalRefusal('Invalid intent shape');
const [, step, method, path, requestFingerprint, key] = record;
if (!/^[a-z][a-z0-9_-]*$/.test(step) || this.intents.has(step) || this.adoptedValues.has(step) || !this.allowed.has(step) || !same(this.allowed.get(step), [method, path]) || !/^[0-9A-F]{64}$/.test(requestFingerprint) || [...this.intents.keys()].some(name => !this.savedValues.has(name)))
throw new JournalRefusal('Invalid, future or repeated intent');
if ((method === 'POST' && !/^[0-9a-f]{32}$/.test(key)) || (method !== 'POST' && key !== '')) throw new JournalRefusal('Invalid persisted action key');
this.intents.set(step, { method, path, request_fingerprint: requestFingerprint, idempotency_key: key });
} else if (record[0] === 'A') {
const [, step, count, ...pairs] = record;
if (record.length < 3 || !/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n * BigInt(count) || !this.intents.has(step) || this.savedValues.has(step))
throw new JournalRefusal('ACK without exactly one prior intent');
const names = pairs.filter((_, index) => index % 2 === 0);
if (!same(names, [...new Set(names)].sort()) || names.some(name => !/^[a-z][a-z0-9_]*$/.test(name) || ['api_key', 'exhibitday_api_key'].includes(name)))
throw new JournalRefusal('ACK fields must be unique sorted secret-free identifiers');
this.savedValues.set(step, Object.fromEntries(names.map((name, index) => [name, pairs[index * 2 + 1]])));
} else if (record[0] === 'S') {
if (record.length < 6) throw new JournalRefusal('Invalid read-adoption shape');
const [,step,method,path,readFingerprint,count,...pairs] = record;
const completed = new Set([...this.savedValues.keys(),...this.adoptedValues.keys()]), order = [...this.allowed.keys()];
if (completed.size >= order.length || order.slice(0,completed.size).some(name=>!completed.has(name)) || step !== order[completed.size] || [...this.intents.keys()].some(name=>!this.savedValues.has(name))) throw new JournalRefusal('Adopt only the exact next setup action without any pending intent');
const target = this.allowed.get(step), expected = (same(target,['POST','/v1/events']) || step==='update_event' && same(target,['PATCH','/v1/events'])) ? '/v1/events/info' : same(target,['POST','/v1/tasks/sections']) ? '/v1/tasks/sections/info' : null;
if (method !== 'GET' || expected === null || path !== expected) throw new JournalRefusal('Adoption requires the exact source-bound single Event or section read');
if (!/^(0|[1-9][0-9]*)$/.test(count) || BigInt(pairs.length) !== 2n*BigInt(count)) throw new JournalRefusal('Invalid read-adoption field count');
const names=pairs.filter((_,i)=>i%2===0), fields=expected==='/v1/events/info'?['id','integration_metadata_field_1']:['event_id','id','name'];
if (!same(names,fields)) throw new JournalRefusal('Read-adoption fields must match the exact source tuple');
const saved=Object.fromEntries(names.map((name,i)=>[name,pairs[2*i+1]]));
for (const name of ['id','event_id']) if (Object.hasOwn(saved,name) && (!/^[1-9][0-9]*$/.test(saved[name]) || BigInt(saved[name])>9223372036854775807n)) throw new JournalRefusal('Read-adoption IDs must be exact positive Int64 strings');
if (fields.some(name=>!['id','event_id'].includes(name)&&saved[name]==='') || readFingerprint!==fingerprint(saved)) throw new JournalRefusal('Read-adoption material must be complete and fingerprint-bound');
this.adoptedValues.set(step,saved);
} else throw new JournalRefusal('Unknown journal transition');
}
requireActive() {
if (!this.owned || this.fd === null || this.identity === null || this.tainted) throw new JournalRefusal('Journal is closed or its IO outcome needs reconciliation');
const current = fs.lstatSync(this.lock, { bigint: true });
if (current.dev !== this.identity.dev || current.ino !== this.identity.ino || ascii(fs.readFileSync(this.lock)) !== this.owner)
throw new JournalRefusal('Journal lock was replaced; stop without deleting it');
}
append(record) {
this.requireActive(); const raw = frame(record); let target;
try { target = fs.openSync(this.path, 'a'); writeAll(target, raw); fs.fsyncSync(target); }
catch (error) { this.tainted = true; throw error; }
finally { if (target !== undefined) fs.closeSync(target); }
}
acknowledged(step) { this.requireActive(); return this.savedValues.has(step); }
saved(step) { this.requireActive(); if (!this.savedValues.has(step)) throw new JournalRefusal('No acknowledged state exists'); return { ...this.savedValues.get(step) }; }
completed(step) { this.requireActive(); return this.savedValues.has(step)||this.adoptedValues.has(step); }
adopted(step) { this.requireActive(); return this.adoptedValues.has(step); }
recorded(step) { this.requireActive(); if(!this.completed(step))throw new JournalRefusal('No completed write or read-adoption exists');return {...(this.savedValues.get(step)||this.adoptedValues.get(step))}; }
adopt(step,method,path,saved) {
this.requireActive(); const names=Object.keys(saved).sort(),record=['S',step,method,path,fingerprint(saved),String(names.length)];
for(const name of names)record.push(name,saved[name]);
const old=new Map(this.adoptedValues);try{this.apply(record);strings(record);}finally{this.adoptedValues=old;}
this.append(record);this.apply(record);
}
begin(step, method, path, requestFingerprint) {
this.requireActive(); if (this.intents.has(step)) throw new JournalRefusal('Never blindly repeat an existing action');
const key = method === 'POST' ? crypto.randomBytes(16).toString('hex') : '', record = ['I', step, method, path, requestFingerprint, key];
const old = new Map(this.intents); try { this.apply(record); } finally { this.intents = old; }
this.append(record); this.apply(record); return { ...this.intents.get(step) };
}
acknowledge(step, saved) {
this.requireActive(); const names = Object.keys(saved).sort(), record = ['A', step, String(names.length)];
for (const name of names) record.push(name, saved[name]);
const old = new Map(this.savedValues); try { this.apply(record); strings(record); } finally { this.savedValues = old; }
this.append(record); this.apply(record);
}
close() {
if (!this.owned) return;
if (this.tainted) { fs.closeSync(this.fd); this.fd = null; this.owned = false; return; }
try { this.requireActive(); }
catch (error) { fs.closeSync(this.fd); this.fd = null; this.owned = false; throw error; }
fs.closeSync(this.fd); this.fd = null; this.owned = false; fs.unlinkSync(this.lock);
}
}
function journal_values(value) {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.values(value).some(item=>typeof item!=='string')) throw new JournalRefusal('Saved/fingerprint values must be exact strings');
return {...value};
}
function journal_acknowledge(job,step,saved) { job.acknowledge(step,journal_values(saved)); }
function journal_acknowledged(job,step) { return job.acknowledged(step); }
function journal_adopt(job,step,method,path,saved){job.adopt(step,method,path,journal_values(saved));}
function journal_begin(job,step,method,path,requestFingerprint) { return job.begin(step,method,path,requestFingerprint); }
function journal_completed(job,step){return job.completed(step);}
function journal_fingerprint(value) { return fingerprint(journal_values(value)); }
function journal_recorded(job,step){return job.recorded(step);}
function not_value(value) { if (typeof value !== "boolean") throw new Error("Expected a Boolean"); return !value; }
function open_journal(path,base,workspace,slug,job,inputFingerprint,writes,mode) { return new Journal(path,base,workspace,slug,job,inputFingerprint,writes,mode); }
function optional(name, fallback) { const value = process.env[name]; return value === undefined || value === "" ? fallback : value; }
function page_size(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 2147483647n) throw new Error("Page size must be a positive int32"); return value; }
function parse_json(value){
const result=JSON.parse(value),stack=[];
for(const match of value.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\],]/gs)){
const token=match[0];
if(token==='{')stack.push({object:true,key:true,names:new Set()});
else if(token==='[')stack.push({object:false});
else if(token==='}'||token===']')stack.pop();
else if(token===','){if(stack.length&&stack.at(-1).object)stack.at(-1).key=true;}
else if(stack.length&&stack.at(-1).object&&stack.at(-1).key){const frame=stack.at(-1),name=JSON.parse(token);if(frame.names.has(name))throw new Error('Duplicate JSON input property');frame.names.add(name);frame.key=false;}
}
function finite(node){if(typeof node==='number'&&!Number.isFinite(node))throw new Error('Use finite JSON numbers');if(node&&typeof node==='object')for(const item of Object.values(node))finite(item);}
finite(result);return result;
}
function positive_id(value) { if (!/^[1-9][0-9]*$/.test(value) || BigInt(value) > 9223372036854775807n) throw new Error("Use a positive record ID"); return value; }
function print_value(value) { console.log(typeof value === "string" ? value : JSON.stringify(value)); }
function require_condition(value, message) { if (value !== true) throw new Error(message); }
function required(name) { const value = process.env[name]; if (value === undefined || !value.trim()) throw new Error("Set " + name); return value; }
function response_status(value) { return String(value.status); }
function single(value){const rows=items(value);if(rows.length!==1)throw new Error('Expected exactly one selected record');return rows[0];}
function text(value) { if (value === null || value === undefined) return ""; if (["string", "boolean", "bigint"].includes(typeof value)) return String(value); throw new Error("Expected a scalar response value"); }
function validate_crm_event_inputs(key, name, start, end) {
const boundary = /^[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]$/;
for (const [value,label,limit] of [[name,'EXHIBITDAY_EVENT_NAME',500],[key,'EXHIBITDAY_EXTERNAL_EVENT_KEY',3000]]) {
utf8(value);
if (!value || boundary.test(value)) throw new JournalRefusal('Remove whitespace at the start or end of ' + label);
if (value.length > limit) throw new JournalRefusal(label + ' exceeds ' + limit + ' UTF-16 code units');
}
if (/[<>\r\n]/.test(name) || name.toLowerCase() === 'null')
throw new JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null');
for (const [value,label] of [[start,'EXHIBITDAY_START_DATE'],[end,'EXHIBITDAY_END_DATE']]) {
const time = new Date(value + 'T00:00:00Z');
if (value.length !== 10 || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)
|| value < '1753-01-01' || Number.isNaN(time.getTime()) || time.toISOString().slice(0,10) !== value)
throw new JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01');
}
if (end < start) throw new JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE');
}
async function main() {
let external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY");
let desired_event_name = required("EXHIBITDAY_EVENT_NAME");
let desired_start_date = required("EXHIBITDAY_START_DATE");
let desired_end_date = required("EXHIBITDAY_END_DATE");
let desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON");
let desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning");
let setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100"));
let desired_setup_dates = items(parse_json(desired_dates_json));
validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date);
let journal_path = required("EXHIBITDAY_JOURNAL");
let stable_job_id = required("EXHIBITDAY_JOB_ID");
let job_mode = optional("EXHIBITDAY_JOB_MODE", "resume");
let setup_workspace_response = await call("workspace_binding", {}, null, null);
require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let setup_workspace = setup_workspace_response.body;
let owned_workspace_id = positive_id(text(field(setup_workspace, "id")));
let setup_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json});
let setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, [["create_event", "POST", "/v1/events"], ["update_event", "PATCH", "/v1/events"], ["create_section", "POST", "/v1/tasks/sections"], ["save_dates", "PATCH", "/v1/events/dates"]], job_mode);
try {
let setup_event_id = "";
let setup_section_id = "";
let recorded_section_name = desired_section_name;
if (journal_completed(setup_job, "create_event")) {
let recorded_event = journal_recorded(setup_job, "create_event");
setup_event_id = positive_id(text(field(recorded_event, "id")));
require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.");
} else {
let event_search_offset = "0";
let event_search_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size};
while (true) {
event_search_query["$offset"] = event_search_offset;
let event_search_response = await call("find_existing", event_search_query, null, null);
require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let event_search_page = event_search_response.body;
let event_search_rows = items(field(event_search_page, "list_data"));
require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.");
require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.");
require_condition(either(equal(field(event_search_page, "has_more"), true), equal(field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value.");
for (const event_search_row of items(event_search_rows)) {
if (equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key)) {
let event_search_candidate_id = positive_id(text(field(event_search_row, "id")));
if (is_present(setup_event_id)) {
require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.");
}
setup_event_id = event_search_candidate_id;
}
}
if (equal(field(event_search_page, "has_more"), false)) {
break;
}
require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.");
event_search_offset = add_offset(event_search_offset, count(event_search_rows));
}
if (not_value(is_present(setup_event_id))) {
let event_write_fingerprint = journal_fingerprint({"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key});
let event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint);
let event_create_response = await call("create_event", {}, {"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key")));
require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let created_event = event_create_response.body;
setup_event_id = positive_id(text(field(created_event, "id")));
require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.");
require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.");
journal_acknowledge(setup_job, "create_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key});
}
}
let event_confirmation_response = await call("confirm_event", {"id": setup_event_id, "$include_record_revision": "true"}, null, null);
require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let confirmed_setup_event = event_confirmation_response.body;
require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.");
if (not_value(journal_completed(setup_job, "create_event"))) {
journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", {"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))});
}
let setup_event_revision = text(field(confirmed_setup_event, "record_revision"));
require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.");
require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.");
if (journal_completed(setup_job, "update_event")) {
let recorded_event_update = journal_recorded(setup_job, "update_event");
require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.");
require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.");
} else {
if (both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) {
journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", {"id": setup_event_id, "integration_metadata_field_1": external_event_key});
} else {
require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.");
let event_update_body = {"id": setup_event_id, "expected_revision": setup_event_revision};
if (not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name))) {
event_update_body["name"] = desired_event_name;
}
if (not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date))) {
event_update_body["start_date"] = desired_start_date;
}
if (not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) {
event_update_body["end_date"] = desired_end_date;
}
let event_update_fingerprint = journal_fingerprint(event_update_body);
journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint);
let event_update_response = await call("update_event", {}, event_update_body, null);
require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let event_update_ack = event_update_response.body;
let event_updated_revision = text(field(event_update_ack, "record_revision"));
require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.");
journal_acknowledge(setup_job, "update_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision});
}
}
let event_update_verify_response = await call("verify_event_update", {"id": setup_event_id}, null, null);
require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let verified_setup_event = event_update_verify_response.body;
require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.");
if (journal_completed(setup_job, "create_section")) {
let recorded_section = journal_recorded(setup_job, "create_section");
setup_section_id = positive_id(text(field(recorded_section, "id")));
require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.");
recorded_section_name = text(field(recorded_section, "name"));
} else {
let section_search_offset = "0";
let section_search_query = {"filter_by_event_id": setup_event_id, "$limit": setup_page_size};
while (true) {
section_search_query["$offset"] = section_search_offset;
let section_search_response = await call("find_section", section_search_query, null, null);
require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let section_search_page = section_search_response.body;
let section_search_rows = items(field(section_search_page, "list_data"));
require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.");
require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.");
require_condition(either(equal(field(section_search_page, "has_more"), true), equal(field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value.");
for (const section_search_row of items(section_search_rows)) {
require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.");
if (equal(text(field(section_search_row, "name")), desired_section_name)) {
let section_search_candidate_id = positive_id(text(field(section_search_row, "id")));
if (is_present(setup_section_id)) {
require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.");
}
setup_section_id = section_search_candidate_id;
}
}
if (equal(field(section_search_page, "has_more"), false)) {
break;
}
require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.");
section_search_offset = add_offset(section_search_offset, count(section_search_rows));
}
if (not_value(is_present(setup_section_id))) {
let section_write_fingerprint = journal_fingerprint({"event_id": setup_event_id, "name": desired_section_name});
let section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint);
let section_create_response = await call("create_section", {}, {"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key")));
require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let created_section = section_create_response.body;
setup_section_id = positive_id(text(field(created_section, "id")));
require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.");
recorded_section_name = text(field(created_section, "name"));
require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.");
journal_acknowledge(setup_job, "create_section", {"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name});
}
}
let section_confirmation_response = await call("confirm_section", {"id": setup_section_id}, null, null);
require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let confirmed_setup_section = section_confirmation_response.body;
require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.");
if (not_value(journal_completed(setup_job, "create_section"))) {
journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", {"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))});
}
let setup_dates_response = await call("read_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, null, null);
require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let setup_dates_page = setup_dates_response.body;
require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.");
let setup_dates_group = single(field(setup_dates_page, "list_data"));
require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.");
let setup_dates_revision = text(field(setup_dates_group, "record_revision"));
require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.");
if (journal_completed(setup_job, "save_dates")) {
let recorded_dates = journal_recorded(setup_job, "save_dates");
require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.");
} else {
let setup_dates_fingerprint = journal_fingerprint({"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision});
journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint);
let setup_dates_save_response = await call("save_dates", {}, {"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, null);
require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let setup_dates_ack = setup_dates_save_response.body;
let setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision"));
require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.");
journal_acknowledge(setup_job, "save_dates", {"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision});
}
let setup_dates_verify_response = await call("verify_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1"}, null, null);
require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let setup_dates_verify_page = setup_dates_verify_response.body;
require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.");
let setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data"));
require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.");
require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.");
let setup_event_readback_response = await call("event_readback", {"id": setup_event_id}, null, null);
require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
let setup_event_readback = setup_event_readback_response.body;
require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.");
require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.");
let planning_section_present = false;
for (const setup_event_section of items(items(field(setup_event_readback, "task_sections")))) {
if (equal(text(field(setup_event_section, "id")), setup_section_id)) {
planning_section_present = true;
}
}
require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.");
print_value({"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"});
} finally {
setup_job.close();
}
}
if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; });
module.exports = { main };
# Python 3; standard library only. Set EXHIBITDAY_API_KEY before running.
import http.client
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
BASE = "https://api.exhibitday.com/v1"
SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}")
API_KEY = os.environ["EXHIBITDAY_API_KEY"]
if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY):
raise RuntimeError("Use the API key as one ASCII header value without control characters")
if not API_KEY.strip():
raise RuntimeError("Set EXHIBITDAY_API_KEY")
def decode_json(text):
if SPEC["preserveNumbers"]:
# Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact.
text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?',
lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text)
return json.loads(text)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, file, code, message, headers, new_url):
return None
OPENER = urllib.request.build_opener(NoRedirect())
def transport(method, url, headers, data):
request = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with OPENER.open(request, timeout=30) as response:
return response.status, response.read(), dict(response.headers)
except urllib.error.HTTPError as response:
try:
return response.code, response.read(), dict(response.headers)
finally:
response.close()
class ApiError(RuntimeError):
"""An API error response. Branch on error_code (and status), never on the message text.
uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied."""
def __init__(self, status, body, uncertain=False):
self.status = status
self.uncertain = uncertain
self.error_code = body.get("error_code") if isinstance(body, dict) else None
super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})"
if isinstance(body, dict) else "HTTP " + str(status) if status else "No response")
def call(name, params=None, body=None, key=None):
route = SPEC["requests"][name]
headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"}
if route["method"] == "POST":
if not key: raise RuntimeError("Persist a logical create key before sending POST")
headers["Idempotency-Key"] = key
data = None if body is None else json.dumps(body).encode("utf-8")
if data is not None:
headers["Content-Type"] = "application/json"
query = urllib.parse.urlencode(params or {})
url = BASE + route["path"] + ("?" + query if query else "")
# Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
# server error is never resent blindly: it may already have been applied, so the caller reads the record first.
resend = route["method"] == "GET"
for attempt in range(5):
try:
status, raw, response_headers = transport(route["method"], url, headers, data)
except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException):
if not resend:
raise ApiError(0, None, uncertain=True)
if attempt == 4:
raise
time.sleep(2 ** attempt)
continue
response_headers = {k.lower(): v for k, v in response_headers.items()}
result = None
if status != 304 and raw:
try:
result = decode_json(raw.decode("utf-8"))
except (ValueError, UnicodeError):
if status < 400:
raise RuntimeError("Expected a JSON success response")
if status >= 500 and not resend:
raise ApiError(status, result, uncertain=True)
retry = resend and (status == 429 or status >= 500)
if retry:
if attempt == 4:
raise RuntimeError("Retry limit reached; check the request outcome before starting a new create")
delay = response_headers.get("retry-after", str(2 ** attempt))
time.sleep(max(0, float(delay)))
continue
if status >= 400:
raise ApiError(status, result)
return {"status": status, "body": result, "headers": response_headers, "raw": raw}
raise RuntimeError("Retry limit reached")
def add_offset(offset, received):
result = int(offset) + received
if received <= 0 or result > 2147483647: raise RuntimeError("Cannot advance this int32 offset; reconcile the query")
return str(result)
def both(left,right):
return left and right
def items(value):
if not isinstance(value, list): raise RuntimeError("Expected a JSON array")
return value
def count(value):
return len(items(value))
def deep_equal(left,right):
if type(left) is not type(right): return False
if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left)
if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right))
return left==right
def either(left, right):
if not isinstance(left, bool) or not isinstance(right, bool): raise RuntimeError("Expected Boolean criteria")
return left or right
def equal(left, right):
return type(left) is type(right) and left == right
def field(value, name):
if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name)
return value[name]
def is_empty(value):
return count(value) == 0
def is_present(value):
return value is not None and value != ""
"""Strict private client journal reference; no transport or application dependency."""
from pathlib import Path
import hashlib
import os
import re
import secrets
from urllib.parse import urlsplit
PREAMBLE=b'EXHIBITDAY-GUIDE-JOURNAL 1\n'
class JournalRefusal(RuntimeError):
pass
def utf8(value):
if not isinstance(value,str):raise JournalRefusal('Journal fields are exact strings')
return value.encode('utf-8',errors='strict')
def strings(values):
raw=bytearray()
for value in values:
item=utf8(value);raw.extend(str(len(item)).encode('ascii'));raw.extend(b':');raw.extend(item)
return bytes(raw)
def read_strings(raw):
values=[];offset=0
while offset<len(raw):
end=raw.find(b':',offset)
if end<0:raise JournalRefusal('Incomplete journal string length')
length=raw[offset:end]
if not re.fullmatch(b'0|[1-9][0-9]*',length):raise JournalRefusal('Noncanonical journal string length')
size=int(length);offset=end+1
if size>len(raw)-offset:raise JournalRefusal('Incomplete journal string')
values.append(raw[offset:offset+size].decode('utf-8',errors='strict'));offset+=size
return values
def digest(raw):return hashlib.sha256(raw).hexdigest().upper()
def fingerprint(pairs):
values=[]
for name,value in sorted(pairs.items()):
if not re.fullmatch('[A-Za-z0-9_.-]+',name):raise JournalRefusal('Fingerprint field names must be explicit ASCII identifiers')
if name.lower() in ('api_key','exhibitday_api_key'):raise JournalRefusal('Never fingerprint the API key')
values.extend((name,value))
return digest(strings(values))
def frame(values):
raw=strings(values)
return str(len(raw)).encode('ascii')+b' '+digest(raw).encode('ascii')+b'\n'+raw+b'\n'
def decode(raw):
if not raw.startswith(PREAMBLE):raise JournalRefusal('Unknown or incomplete journal version')
offset=len(PREAMBLE);records=[]
while offset<len(raw):
end=raw.find(b'\n',offset)
if end<0:raise JournalRefusal('Incomplete journal frame header; reconcile before retry')
match=re.fullmatch(b'(0|[1-9][0-9]*) ([0-9A-F]{64})',raw[offset:end])
if match is None:raise JournalRefusal('Invalid journal frame header')
size=int(match[1]);offset=end+1
if size>=len(raw)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry')
payload=raw[offset:offset+size];offset+=size
if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry')
records.append(read_strings(payload));offset+=1
return records
class Journal:
def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"):
self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={};self.adopted_values={};self.order=[]
address=urlsplit(base)
if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug')
if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint')
if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job")
self.allowed={};manifest=[]
for step,method,route in writes:
if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest')
self.allowed[step]=(method,route);self.order.append(step);manifest.extend((step,method,route))
if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal')
self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))]
strings(self.header)
try:
self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True
except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock')
try:
self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd)
if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write')
os.fsync(self.fd)
if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file')
if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job")
if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical job")
if mode=="new":
with open(self.path,'xb',buffering=0)as target:
target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno())
records=decode(self.path.read_bytes())
if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs')
for record in records[1:]:self.apply(record)
if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry')
except BaseException:
self.close();raise
def apply(self,record):
if not record:raise JournalRefusal('Empty journal record')
if record[0]=='I':
if len(record)!=6:raise JournalRefusal('Invalid intent shape')
_,step,method,path,request_fingerprint,key=record
if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or step in self.adopted_values or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent')
if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key')
self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key}
elif record[0]=='A':
if len(record)<3:raise JournalRefusal('Invalid ACK shape')
_,step,count,*pairs=record
if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent')
names=pairs[::2]
if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers')
self.saved_values[step]=dict(zip(names,pairs[1::2]))
elif record[0]=='S':
if len(record)<6:raise JournalRefusal('Invalid read-adoption shape')
_,step,method,path,read_fingerprint,count,*pairs=record
completed=set(self.saved_values)|set(self.adopted_values)
if len(completed)>=len(self.order) or completed!=set(self.order[:len(completed)]) or step!=self.order[len(completed)] or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Adopt only the exact next setup action without any pending intent')
target=self.allowed.get(step)
expected='/v1/events/info'if (target==('POST','/v1/events') or step=='update_event' and target==('PATCH','/v1/events'))else '/v1/tasks/sections/info'if target==('POST','/v1/tasks/sections')else None
if method!='GET' or expected is None or path!=expected:raise JournalRefusal('Adoption requires the exact source-bound single Event or section read')
if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count):raise JournalRefusal('Invalid read-adoption field count')
names=pairs[::2];fields=['id','integration_metadata_field_1']if expected=='/v1/events/info'else ['event_id','id','name']
if names!=fields:raise JournalRefusal('Read-adoption fields must match the exact source tuple')
saved=dict(zip(names,pairs[1::2]))
for name in ('id','event_id'):
if name in saved and (not re.fullmatch('[1-9][0-9]*',saved[name])or int(saved[name])>9223372036854775807):raise JournalRefusal('Read-adoption IDs must be exact positive Int64 strings')
if any(saved[name]==''for name in fields if name not in ('id','event_id'))or read_fingerprint!=fingerprint(saved):raise JournalRefusal('Read-adoption material must be complete and fingerprint-bound')
self.adopted_values[step]=saved
else:raise JournalRefusal('Unknown journal transition')
def append(self,record):
# The reader commits state only after complete length/digest recognition.
# A torn append is retained and refused, never silently truncated.
self.require_active();raw=frame(record)
try:
with open(self.path,'ab',buffering=0)as target:
view=memoryview(raw)
while view:
written=target.write(view)
if not written:raise OSError('Journal write did not advance')
view=view[written:]
os.fsync(target.fileno())
except BaseException:
self.tainted=True;raise
def require_active(self):
if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation')
current=self.lock.stat(follow_symlinks=False)
if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it')
def acknowledged(self,step):
self.require_active();return step in self.saved_values
def saved(self,step):
self.require_active()
if step not in self.saved_values:raise JournalRefusal('No acknowledged state exists for this step')
return dict(self.saved_values[step])
def completed(self,step):
self.require_active();return step in self.saved_values or step in self.adopted_values
def recorded(self,step):
self.require_active()
if step in self.saved_values:return dict(self.saved_values[step])
if step in self.adopted_values:return dict(self.adopted_values[step])
raise JournalRefusal('No completed write or read-adoption exists')
def adopted(self,step):
self.require_active();return step in self.adopted_values
def adopt(self,step,source_method,source_path,saved):
self.require_active()
record=['S',step,source_method,source_path,fingerprint(saved),str(len(saved))]
for name,value in sorted(saved.items()):record.extend((name,value))
old={name:dict(value)for name,value in self.adopted_values.items()}
try:self.apply(record);strings(record)
finally:self.adopted_values=old
self.append(record);self.apply(record)
def begin(self,step,method,path,request_fingerprint):
self.require_active()
if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent')
key=secrets.token_hex(16)if method=='POST'else''
record=['I',step,method,path,request_fingerprint,key]
# Validate on an isolated state before touching the file.
old=dict(self.intents)
try:self.apply(record)
finally:self.intents=old
self.append(record);self.apply(record)
return dict(self.intents[step])
def acknowledge(self,step,saved):
self.require_active()
record=['A',step,str(len(saved))]
for name,value in sorted(saved.items()):record.extend((name,value))
old={name:dict(value)for name,value in self.saved_values.items()}
try:self.apply(record);strings(record)
finally:self.saved_values=old
self.append(record);self.apply(record)
def close(self):
if self.owned:
if self.tainted:
os.close(self.fd);self.fd=None;self.owned=False
return # Retain this lock after failed journal IO; manual reconciliation is required.
try:self.require_active()
except BaseException:
os.close(self.fd);self.fd=None;self.owned=False;raise
os.close(self.fd);self.fd=None;self.owned=False
self.lock.unlink()
def __enter__(self):return self
def __exit__(self,*args):self.close()
def journal_values(value):
if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()):
raise JournalRefusal('Saved/fingerprint values must be exact string fields')
return dict(value)
def journal_acknowledge(job, step, saved):
job.acknowledge(step,journal_values(saved))
def journal_acknowledged(job, step):
return job.acknowledged(step)
def journal_adopt(job,step,method,path,saved):job.adopt(step,method,path,journal_values(saved))
def journal_begin(job, step, method, path, request_fingerprint):
return job.begin(step,method,path,request_fingerprint)
def journal_completed(job,step):return job.completed(step)
def journal_fingerprint(value):
return fingerprint(journal_values(value))
def journal_recorded(job,step):return job.recorded(step)
def not_value(value):
if not isinstance(value, bool): raise RuntimeError("Expected a Boolean")
return not value
def open_journal(path, base, workspace, slug, job, input_fingerprint, writes, mode):
return Journal(path,base,workspace,slug,job,input_fingerprint,writes,mode)
def optional(name, fallback):
value = os.environ.get(name)
return fallback if value is None or value == "" else value
def page_size(value):
if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32")
return value
def parse_json(value):
import math
def pairs(values):
result={}
for key,item in values:
if key in result:raise ValueError('Duplicate JSON input property')
result[key]=item
return result
def number(value):
result=float(value)
if not math.isfinite(result):raise ValueError('Use finite JSON numbers')
return result
def invalid(value):raise ValueError('Use standard JSON values')
return json.loads(value,object_pairs_hook=pairs,parse_float=number,parse_constant=invalid)
def positive_id(value):
if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID")
return value
def print_value(value):
print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False))
def require_condition(value, message):
if value is not True: raise RuntimeError(message)
def required(name):
value = os.environ.get(name)
if value is None or not value.strip(): raise RuntimeError("Set " + name)
return value
def response_status(value):
return str(value["status"])
def single(value):
rows=items(value)
if len(rows)!=1: raise RuntimeError('Expected exactly one selected record')
return rows[0]
def text(value):
if value is None: return ""
if isinstance(value, str): return value
if isinstance(value, bool): return "true" if value else "false"
if isinstance(value, int): return str(value)
raise RuntimeError("Expected a scalar response value")
def validate_crm_event_inputs(key, name, start, end):
from datetime import date
spaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000'
for value, label, limit in ((name, 'EXHIBITDAY_EVENT_NAME', 500), (key, 'EXHIBITDAY_EXTERNAL_EVENT_KEY', 3000)):
utf8(value)
if not value or value != value.strip(spaces):
raise JournalRefusal('Remove whitespace at the start or end of ' + label)
if len(value.encode('utf-16-le')) // 2 > limit:
raise JournalRefusal(label + ' exceeds ' + str(limit) + ' UTF-16 code units')
if any(ch in name for ch in '<>\r\n') or name.lower() == 'null':
raise JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null')
for value, label in ((start, 'EXHIBITDAY_START_DATE'), (end, 'EXHIBITDAY_END_DATE')):
try:
valid = re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value) and date.fromisoformat(value).year >= 1753
except ValueError:
valid = False
if not valid:
raise JournalRefusal(label + ' must be a calendar date in YYYY-MM-DD on or after 1753-01-01')
if end < start:
raise JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE')
def main():
external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY")
desired_event_name = required("EXHIBITDAY_EVENT_NAME")
desired_start_date = required("EXHIBITDAY_START_DATE")
desired_end_date = required("EXHIBITDAY_END_DATE")
desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON")
desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning")
setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100"))
desired_setup_dates = items(parse_json(desired_dates_json))
validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date)
journal_path = required("EXHIBITDAY_JOURNAL")
stable_job_id = required("EXHIBITDAY_JOB_ID")
job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
setup_workspace_response = call("workspace_binding", {}, None, None)
require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_workspace = setup_workspace_response["body"]
owned_workspace_id = positive_id(text(field(setup_workspace, "id")))
setup_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json})
setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, [["create_event", "POST", "/v1/events"], ["update_event", "PATCH", "/v1/events"], ["create_section", "POST", "/v1/tasks/sections"], ["save_dates", "PATCH", "/v1/events/dates"]], job_mode)
try:
setup_event_id = ""
setup_section_id = ""
recorded_section_name = desired_section_name
if journal_completed(setup_job, "create_event"):
recorded_event = journal_recorded(setup_job, "create_event")
setup_event_id = positive_id(text(field(recorded_event, "id")))
require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.")
else:
event_search_offset = "0"
event_search_query = {"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size}
while True:
event_search_query["$offset"] = event_search_offset
event_search_response = call("find_existing", event_search_query, None, None)
require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
event_search_page = event_search_response["body"]
event_search_rows = items(field(event_search_page, "list_data"))
require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.")
require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.")
require_condition(either(equal(field(event_search_page, "has_more"), True), equal(field(event_search_page, "has_more"), False)), "Expected a Boolean has_more value.")
for event_search_row in items(event_search_rows):
if equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key):
event_search_candidate_id = positive_id(text(field(event_search_row, "id")))
if is_present(setup_event_id):
require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.")
setup_event_id = event_search_candidate_id
if equal(field(event_search_page, "has_more"), False):
break
require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.")
event_search_offset = add_offset(event_search_offset, count(event_search_rows))
if not_value(is_present(setup_event_id)):
event_write_fingerprint = journal_fingerprint({"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key})
event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint)
event_create_response = call("create_event", {}, {"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key")))
require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
created_event = event_create_response["body"]
setup_event_id = positive_id(text(field(created_event, "id")))
require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.")
require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.")
journal_acknowledge(setup_job, "create_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key})
event_confirmation_response = call("confirm_event", {"id": setup_event_id, "$include_record_revision": "true"}, None, None)
require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
confirmed_setup_event = event_confirmation_response["body"]
require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.")
if not_value(journal_completed(setup_job, "create_event")):
journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", {"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))})
setup_event_revision = text(field(confirmed_setup_event, "record_revision"))
require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.")
require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.")
if journal_completed(setup_job, "update_event"):
recorded_event_update = journal_recorded(setup_job, "update_event")
require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.")
require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.")
else:
if both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)):
journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", {"id": setup_event_id, "integration_metadata_field_1": external_event_key})
else:
require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.")
event_update_body = {"id": setup_event_id, "expected_revision": setup_event_revision}
if not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name)):
event_update_body["name"] = desired_event_name
if not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)):
event_update_body["start_date"] = desired_start_date
if not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)):
event_update_body["end_date"] = desired_end_date
event_update_fingerprint = journal_fingerprint(event_update_body)
journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint)
event_update_response = call("update_event", {}, event_update_body, None)
require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
event_update_ack = event_update_response["body"]
event_updated_revision = text(field(event_update_ack, "record_revision"))
require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.")
journal_acknowledge(setup_job, "update_event", {"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision})
event_update_verify_response = call("verify_event_update", {"id": setup_event_id}, None, None)
require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
verified_setup_event = event_update_verify_response["body"]
require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.")
if journal_completed(setup_job, "create_section"):
recorded_section = journal_recorded(setup_job, "create_section")
setup_section_id = positive_id(text(field(recorded_section, "id")))
require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.")
recorded_section_name = text(field(recorded_section, "name"))
else:
section_search_offset = "0"
section_search_query = {"filter_by_event_id": setup_event_id, "$limit": setup_page_size}
while True:
section_search_query["$offset"] = section_search_offset
section_search_response = call("find_section", section_search_query, None, None)
require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
section_search_page = section_search_response["body"]
section_search_rows = items(field(section_search_page, "list_data"))
require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.")
require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.")
require_condition(either(equal(field(section_search_page, "has_more"), True), equal(field(section_search_page, "has_more"), False)), "Expected a Boolean has_more value.")
for section_search_row in items(section_search_rows):
require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.")
if equal(text(field(section_search_row, "name")), desired_section_name):
section_search_candidate_id = positive_id(text(field(section_search_row, "id")))
if is_present(setup_section_id):
require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.")
setup_section_id = section_search_candidate_id
if equal(field(section_search_page, "has_more"), False):
break
require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.")
section_search_offset = add_offset(section_search_offset, count(section_search_rows))
if not_value(is_present(setup_section_id)):
section_write_fingerprint = journal_fingerprint({"event_id": setup_event_id, "name": desired_section_name})
section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint)
section_create_response = call("create_section", {}, {"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key")))
require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
created_section = section_create_response["body"]
setup_section_id = positive_id(text(field(created_section, "id")))
require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.")
recorded_section_name = text(field(created_section, "name"))
require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.")
journal_acknowledge(setup_job, "create_section", {"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name})
section_confirmation_response = call("confirm_section", {"id": setup_section_id}, None, None)
require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
confirmed_setup_section = section_confirmation_response["body"]
require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.")
if not_value(journal_completed(setup_job, "create_section")):
journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", {"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))})
setup_dates_response = call("read_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, None, None)
require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_page = setup_dates_response["body"]
require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.")
setup_dates_group = single(field(setup_dates_page, "list_data"))
require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.")
setup_dates_revision = text(field(setup_dates_group, "record_revision"))
require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.")
if journal_completed(setup_job, "save_dates"):
recorded_dates = journal_recorded(setup_job, "save_dates")
require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.")
else:
setup_dates_fingerprint = journal_fingerprint({"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision})
journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint)
setup_dates_save_response = call("save_dates", {}, {"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, None)
require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_ack = setup_dates_save_response["body"]
setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision"))
require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.")
journal_acknowledge(setup_job, "save_dates", {"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision})
setup_dates_verify_response = call("verify_dates", {"event_id": setup_event_id, "filter_by_date_type_id": "1"}, None, None)
require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_verify_page = setup_dates_verify_response["body"]
require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), False))), "Expected one complete selected Dates group, without another page.")
setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data"))
require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.")
require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.")
setup_event_readback_response = call("event_readback", {"id": setup_event_id}, None, None)
require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_event_readback = setup_event_readback_response["body"]
require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.")
require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.")
planning_section_present = False
for setup_event_section in items(items(field(setup_event_readback, "task_sections"))):
if equal(text(field(setup_event_section, "id")), setup_section_id):
planning_section_present = True
require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.")
print_value({"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"})
finally:
setup_job.close()
if __name__ == "__main__":
main()
// .NET 8 console program; standard library only. Set EXHIBITDAY_API_KEY.
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
class Program
{
static readonly string BaseUrl = "https://api.exhibitday.com/v1";
static readonly JsonNode Spec = JsonNode.Parse("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}");
static readonly string ApiKey = HeaderKey(Required("EXHIBITDAY_API_KEY"));
static string HeaderKey(string value) { if(value.Any(c=>c<32||c>126))throw new Exception("Use the API key as one ASCII header value without control characters");return value; }
static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) };
internal static Func<HttpRequestMessage, Task<HttpResponseMessage>> Send = request => Client.SendAsync(request);
sealed class Result { public int Status; public JsonNode Body; public Dictionary<string, string> Headers; public string Raw; }
// An API error response. Branch on ErrorCode (and Status), never on the message text.
// Uncertain is true when a PATCH or DELETE got no response or a server error: it may or may not have been applied.
sealed class ApiException : Exception
{
public int Status { get; }
public string ErrorCode { get; }
public bool Uncertain { get; }
public ApiException(int status, string errorCode, string message, bool uncertain = false) : base(message) { Status = status; ErrorCode = errorCode; Uncertain = uncertain; }
}
static string Required(string name)
{ var value = Environment.GetEnvironmentVariable(name); return string.IsNullOrWhiteSpace(value) ? throw new Exception("Set " + name) : value; }
static string Text(JsonNode value) => value == null ? "" :
value is JsonValue scalar && scalar.TryGetValue<string>(out var text) ? text : value.ToJsonString();
static JsonObject Query(params (string Key, string Value)[] values)
{ var result = new JsonObject(); foreach (var value in values) result[value.Key] = value.Value; return result; }
static async Task<Result> Call(string name, JsonObject query = null, JsonNode body = null,
string key = null)
{
var route = Spec["requests"][name];
var method = Text(route["method"]);
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{ ["Authorization"] = "Bearer " + ApiKey, ["Accept"] = "application/json" };
if (method == "POST") { if (string.IsNullOrEmpty(key)) throw new Exception("Persist a logical create key before sending POST"); headers["Idempotency-Key"] = key; }
var data = body?.ToJsonString();
var suffix = query == null ? "" : string.Join("&", query.Select(p => Uri.EscapeDataString(p.Key) + "=" + Uri.EscapeDataString(Text(p.Value))));
var url = BaseUrl + Text(route["path"]) + (suffix.Length == 0 ? "" : "?" + suffix);
// Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
// server error is never resent blindly: it may already have been applied, so the caller reads the record first.
var resend = method == "GET";
for (var attempt = 0; attempt < 5; attempt++)
{
using var request = new HttpRequestMessage(new HttpMethod(method), url);
foreach (var header in headers) request.Headers.TryAddWithoutValidation(header.Key, header.Value);
if (data != null) request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response;
string raw;
try { response = await Send(request); }
catch (Exception error) when (error is HttpRequestException || error is TaskCanceledException)
{ if (!resend) throw new ApiException(0, null, "No response", true); if (attempt == 4) throw; await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt))); continue; }
using (response)
{
try { raw = await response.Content.ReadAsStringAsync(); }
catch (Exception error) when (error is HttpRequestException || error is TaskCanceledException)
{ if (!resend) throw new ApiException(0, null, "No response", true); if (attempt == 4) throw; await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt))); continue; }
var status = (int)response.StatusCode;
var resultHeaders = response.Headers.Concat(response.Content.Headers)
.ToDictionary(h => h.Key.ToLowerInvariant(), h => string.Join(", ", h.Value));
JsonNode result = null;
if (status != 304 && raw.Length > 0)
{
try { result = JsonNode.Parse(raw); }
catch (JsonException) { if (status < 400) throw new Exception("Expected a JSON success response"); }
}
var errorBody = result as JsonObject;
if (status >= 500 && !resend) throw new ApiException(status, errorBody == null ? null : Text(errorBody["error_code"]), "HTTP " + status, true);
var retry = resend && (status == 429 || status >= 500);
if (retry)
{
if (attempt == 4) throw new Exception("Retry limit reached; check the outcome before starting a new create");
var seconds = Math.Pow(2, attempt);
if (resultHeaders.TryGetValue("retry-after", out var requested) &&
double.TryParse(requested, NumberStyles.Float, CultureInfo.InvariantCulture, out var delay) &&
double.IsFinite(delay) && delay >= 0) seconds = delay;
await Task.Delay(TimeSpan.FromSeconds(seconds)); continue;
}
if (status >= 400) throw new ApiException(status, errorBody == null ? null : Text(errorBody["error_code"]), errorBody == null ? "HTTP " + status :
$"{Text(errorBody["error_code"])} {errorBody["error_params"]}: {errorBody["errors"]} (request {Text(errorBody["request_id"])})");
return new Result { Status = status, Body = result, Headers = resultHeaders, Raw = raw };
}
}
throw new Exception("Retry limit reached");
}
static string AddOffset(string offset,long received) { var result=checked(long.Parse(offset,CultureInfo.InvariantCulture)+received);if(received<=0||result>int.MaxValue)throw new Exception("Cannot advance this int32 offset; reconcile the query");return result.ToString(CultureInfo.InvariantCulture); }
static bool Both(bool left,bool right)=>left&&right;
static JsonNode CopyNode(JsonNode value) => value?.DeepClone();
static JsonArray Items(JsonNode value) => value as JsonArray ?? throw new Exception("Expected a JSON array");
static long Count(JsonNode value) => Items(value).Count;
static bool DeepEqual(JsonNode left,JsonNode right)=>JsonNode.DeepEquals(left,right);
static bool Either(bool left,bool right) => left || right;
static object Scalar(object value) { if(value is JsonValue json){if(json.TryGetValue<bool>(out var boolean))return boolean;if(json.TryGetValue<string>(out var text))return text;return json.ToJsonString();}return value; }
static bool Equal(object left,object right) => object.Equals(Scalar(left),Scalar(right));
static JsonNode Field(JsonNode value,string name) { if(value is not JsonObject obj || !obj.TryGetPropertyValue(name,out var item))throw new Exception("Missing response field: "+name);return item; }
static bool IsEmpty(JsonNode value) => Count(value)==0;
static bool IsPresent(string value) => value!=null && value!="";
public sealed class JournalRefusal : Exception { public JournalRefusal(string message) : base(message) {} }
public static class JournalProtocol
{
public static readonly byte[] Preamble = Encoding.ASCII.GetBytes("EXHIBITDAY-GUIDE-JOURNAL 1\n");
static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true);
static bool Match(string value,string pattern) => value != null && System.Text.RegularExpressions.Regex.IsMatch(value,"\\A(?:"+pattern+")\\z",System.Text.RegularExpressions.RegexOptions.CultureInvariant);
public static bool Valid(string value,string pattern) => Match(value,pattern);
static string Ascii(byte[] raw,int start,int count)
{ for(var i=start;i<start+count;i++)if(raw[i]>127)throw new JournalRefusal("Journal framing must be canonical ASCII");return Encoding.ASCII.GetString(raw,start,count); }
public static byte[] Strings(IEnumerable<string> values)
{
using var data=new MemoryStream();
foreach(var value in values){if(value==null)throw new JournalRefusal("Journal fields are exact strings");var item=Utf8.GetBytes(value);var prefix=Encoding.ASCII.GetBytes(item.Length.ToString(CultureInfo.InvariantCulture)+":");data.Write(prefix);data.Write(item);}
return data.ToArray();
}
public static List<string> ReadStrings(byte[] raw)
{
var values=new List<string>();var offset=0;
while(offset<raw.Length){var end=Array.IndexOf(raw,(byte)58,offset);if(end<0)throw new JournalRefusal("Incomplete journal string length");var text=Ascii(raw,offset,end-offset);
if(!Match(text,"0|[1-9][0-9]*")||!long.TryParse(text,NumberStyles.None,CultureInfo.InvariantCulture,out var size))throw new JournalRefusal("Noncanonical journal string length");offset=end+1;
if(size>raw.Length-offset)throw new JournalRefusal("Incomplete journal string");values.Add(Utf8.GetString(raw,offset,(int)size));offset+=(int)size;}
return values;
}
public static string Digest(byte[] raw)=>Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(raw));
public static string Fingerprint(IReadOnlyDictionary<string,string> pairs)
{
var values=new List<string>();foreach(var name in pairs.Keys.OrderBy(n=>n,StringComparer.Ordinal)){
if(!Match(name,"[A-Za-z0-9_.-]+")||new[]{"api_key","exhibitday_api_key"}.Contains(name.ToLowerInvariant()))throw new JournalRefusal("Use explicit secret-free fingerprint names");values.Add(name);values.Add(pairs[name]);}
return Digest(Strings(values));
}
public static byte[] Frame(IEnumerable<string> values)
{
var payload=Strings(values);var header=Encoding.ASCII.GetBytes(payload.Length.ToString(CultureInfo.InvariantCulture)+" "+Digest(payload)+"\n");
using var data=new MemoryStream();data.Write(header);data.Write(payload);data.WriteByte(10);return data.ToArray();
}
public static List<List<string>> Decode(byte[] raw)
{
if(raw.Length<Preamble.Length||!raw.Take(Preamble.Length).SequenceEqual(Preamble))throw new JournalRefusal("Unknown or incomplete journal version");
var offset=Preamble.Length;var records=new List<List<string>>();
while(offset<raw.Length){var end=Array.IndexOf(raw,(byte)10,offset);if(end<0)throw new JournalRefusal("Incomplete frame header; reconcile before retry");var header=Ascii(raw,offset,end-offset);
if(!Match(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"))throw new JournalRefusal("Invalid frame header");var split=header.Split(' ');
if(!long.TryParse(split[0],NumberStyles.None,CultureInfo.InvariantCulture,out var size))throw new JournalRefusal("Invalid frame length");offset=end+1;
if(size>=raw.Length-offset)throw new JournalRefusal("Incomplete frame; reconcile before retry");var payload=raw.AsSpan(offset,(int)size).ToArray();offset+=(int)size;
if(raw[offset]!=10||Digest(payload)!=split[1])throw new JournalRefusal("Journal integrity failed; reconcile before retry");records.Add(ReadStrings(payload));offset++;}
return records;
}
}
public sealed class Journal : IDisposable
{
readonly string path,lockPath,owner;readonly List<string> header;
readonly Dictionary<string,(string Method,string Path)> allowed=new Dictionary<string,(string,string)>(StringComparer.Ordinal);
Dictionary<string,Dictionary<string,string>> intents=new Dictionary<string,Dictionary<string,string>>(StringComparer.Ordinal),savedValues=new Dictionary<string,Dictionary<string,string>>(StringComparer.Ordinal);
Dictionary<string,Dictionary<string,string>> adoptedValues=new Dictionary<string,Dictionary<string,string>>(StringComparer.Ordinal);readonly List<string> order=new List<string>();
FileStream lockStream;bool owned,tainted;DateTime creation;
static FileStream CreatePrivate(string target,FileAccess access,FileShare share)
{
var options=new FileStreamOptions{Mode=FileMode.CreateNew,Access=access,Share=share};
if(!OperatingSystem.IsWindows())options.UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite;
return new FileStream(target,options);
}
public Journal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,IEnumerable<(string Step,string Method,string Path)> writes,string mode="resume")
{
this.path=path;lockPath=path+".lock";owner=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
if(!Uri.TryCreate(apiBase,UriKind.Absolute,out var address)||address.Scheme!="https"&&address.Scheme!="http"||address.UserInfo.Length!=0||address.Query.Length!=0||address.Fragment.Length!=0||!JournalProtocol.Valid(slug,"[a-z][a-z0-9-]*"))throw new JournalRefusal("Use the actual API base and closed guide slug");
if(string.IsNullOrWhiteSpace(job)||!JournalProtocol.Valid(workspace,"[1-9][0-9]*")||!JournalProtocol.Valid(inputFingerprint,"[0-9A-F]{64}"))throw new JournalRefusal("Use actual workspace, stable explicit job ID and exact fingerprint");
if(mode!="new"&&mode!="resume")throw new JournalRefusal("Choose new or resume for this local job");
var manifest=new List<string>();foreach(var write in writes){
if(!JournalProtocol.Valid(write.Step,"[a-z][a-z0-9_-]*")||allowed.ContainsKey(write.Step)||!new[]{"POST","PATCH","DELETE"}.Contains(write.Method)||!JournalProtocol.Valid(write.Path,"/v1/[A-Za-z0-9_/-]+")||write.Path.Contains("//"))throw new JournalRefusal("Use a closed unique write manifest");
allowed.Add(write.Step,(write.Method,write.Path));order.Add(write.Step);manifest.AddRange(new[]{write.Step,write.Method,write.Path});}
if(allowed.Count==0)throw new JournalRefusal("Only write workflows need a restart journal");
header=new List<string>{"H","1",apiBase,workspace,slug,job,inputFingerprint,JournalProtocol.Digest(JournalProtocol.Strings(manifest))};JournalProtocol.Strings(header);
try{lockStream=CreatePrivate(lockPath,FileAccess.ReadWrite,FileShare.Read);owned=true;}
catch(IOException)when(File.Exists(lockPath)){throw new JournalRefusal("This journal is locked; do not overlap jobs or steal a stale lock");}
try{
var token=Encoding.ASCII.GetBytes(owner);lockStream.Write(token);lockStream.Flush(true);creation=File.GetCreationTimeUtc(lockPath);
if(File.Exists(path)&&(File.GetAttributes(path)&FileAttributes.ReparsePoint)!=0)throw new JournalRefusal("Choose a private regular journal file");
if(mode=="resume"&&!File.Exists(path))throw new JournalRefusal("Journal missing: stop and reconcile lost state before starting a new logical job");
if(mode=="new"&&File.Exists(path))throw new JournalRefusal("Journal exists; use resume for the same logical job");
if(mode=="new"){using var output=CreatePrivate(path,FileAccess.Write,FileShare.None);output.Write(JournalProtocol.Preamble);output.Write(JournalProtocol.Frame(header));output.Flush(true);}
var records=JournalProtocol.Decode(File.ReadAllBytes(path));if(records.Count==0||!records[0].SequenceEqual(header))throw new JournalRefusal("Journal workspace/base/guide/job/input binding differs");
foreach(var record in records.Skip(1))Apply(record);if(intents.Keys.Any(step=>!savedValues.ContainsKey(step)))throw new JournalRefusal("Saved intent lacks ACK; stop and reconcile before retry");
}catch{Dispose();throw;}
}
void Apply(IReadOnlyList<string> record)
{
if(record.Count==0)throw new JournalRefusal("Empty journal record");
if(record[0]=="I"){
if(record.Count!=6)throw new JournalRefusal("Invalid intent shape");var step=record[1];var method=record[2];var route=record[3];var fingerprint=record[4];var key=record[5];
if(!JournalProtocol.Valid(step,"[a-z][a-z0-9_-]*")||intents.ContainsKey(step)||adoptedValues.ContainsKey(step)||!allowed.TryGetValue(step,out var expected)||expected!=(method,route)||!JournalProtocol.Valid(fingerprint,"[0-9A-F]{64}")||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Invalid, future or repeated intent");
if(method=="POST"&&!JournalProtocol.Valid(key,"[0-9a-f]{32}")||method!="POST"&&key!="")throw new JournalRefusal("Invalid persisted action key");
intents.Add(step,new Dictionary<string,string>{{"method",method},{"path",route},{"request_fingerprint",fingerprint},{"idempotency_key",key}});
}else if(record[0]=="A"){
if(record.Count<3||!JournalProtocol.Valid(record[2],"0|[1-9][0-9]*")||!long.TryParse(record[2],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-3L)/2||record.Count%2!=1||!intents.ContainsKey(record[1])||savedValues.ContainsKey(record[1]))throw new JournalRefusal("ACK without exactly one prior intent");
var names=record.Skip(3).Where((_,index)=>index%2==0).ToArray();
if(!names.SequenceEqual(names.Distinct(StringComparer.Ordinal).OrderBy(name=>name,StringComparer.Ordinal))||names.Any(name=>!JournalProtocol.Valid(name,"[a-z][a-z0-9_]*")||name=="api_key"||name=="exhibitday_api_key"))throw new JournalRefusal("ACK fields must be unique sorted secret-free identifiers");
var saved=new Dictionary<string,string>(StringComparer.Ordinal);for(var i=0;i<names.Length;i++)saved.Add(names[i],record[4+2*i]);savedValues.Add(record[1],saved);
}else if(record[0]=="S"){
if(record.Count<6)throw new JournalRefusal("Invalid read-adoption shape");var step=record[1];var method=record[2];var route=record[3];var readFingerprint=record[4];
var completed=new HashSet<string>(savedValues.Keys.Concat(adoptedValues.Keys),StringComparer.Ordinal);
if(completed.Count>=order.Count||!completed.SetEquals(order.Take(completed.Count))||step!=order[completed.Count]||intents.Keys.Any(name=>!savedValues.ContainsKey(name)))throw new JournalRefusal("Adopt only the exact next setup action without any pending intent");
var target=allowed[step];var expected=(target==("POST","/v1/events")||step=="update_event"&&target==("PATCH","/v1/events"))?"/v1/events/info":target==("POST","/v1/tasks/sections")?"/v1/tasks/sections/info":null;
if(method!="GET"||expected==null||route!=expected)throw new JournalRefusal("Adoption requires the exact source-bound single Event or section read");
if(!JournalProtocol.Valid(record[5],"0|[1-9][0-9]*")||!long.TryParse(record[5],NumberStyles.None,CultureInfo.InvariantCulture,out var count)||count!=(record.Count-6L)/2||record.Count%2!=0)throw new JournalRefusal("Invalid read-adoption field count");
var names=record.Skip(6).Where((_,index)=>index%2==0).ToArray();var fields=expected=="/v1/events/info"?new[]{"id","integration_metadata_field_1"}:new[]{"event_id","id","name"};
if(!names.SequenceEqual(fields))throw new JournalRefusal("Read-adoption fields must match the exact source tuple");
var saved=new Dictionary<string,string>(StringComparer.Ordinal);for(int i=0;i<names.Length;i++)saved.Add(names[i],record[7+2*i]);
foreach(var name in new[]{"id","event_id"})if(saved.TryGetValue(name,out var value)&&(!JournalProtocol.Valid(value,"[1-9][0-9]*")||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var parsed)||parsed<=0))throw new JournalRefusal("Read-adoption IDs must be exact positive Int64 strings");
if(fields.Any(name=>name!="id"&&name!="event_id"&&string.IsNullOrEmpty(saved[name]))||readFingerprint!=JournalProtocol.Fingerprint(saved))throw new JournalRefusal("Read-adoption material must be complete and fingerprint-bound");
adoptedValues.Add(step,saved);
}else throw new JournalRefusal("Unknown journal transition");
}
void RequireActive()
{
if(!owned||lockStream==null||tainted)throw new JournalRefusal("Journal is closed or IO outcome needs reconciliation");
// FileShare.Read denies write/delete sharing on Windows while this handle
// is held. Token + creation witness guards cooperative ownership. Manual
// replacement during a run is outside the portable compare/unlink claim.
var position=lockStream.Position;lockStream.Position=0;var token=new byte[owner.Length];var count=lockStream.Read(token);lockStream.Position=position;
if(!File.Exists(lockPath)||File.GetCreationTimeUtc(lockPath)!=creation||lockStream.Length!=owner.Length||count!=owner.Length||!token.SequenceEqual(Encoding.ASCII.GetBytes(owner)))throw new JournalRefusal("Journal lock was replaced; stop without deleting it");
}
void Append(IReadOnlyList<string> record)
{
RequireActive();var raw=JournalProtocol.Frame(record);
try{using var output=new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None);output.Write(raw);output.Flush(true);}
catch{tainted=true;throw;}
}
public bool Acknowledged(string step){RequireActive();return savedValues.ContainsKey(step);}
public Dictionary<string,string> Saved(string step){RequireActive();if(!savedValues.ContainsKey(step))throw new JournalRefusal("No acknowledged state exists");return new Dictionary<string,string>(savedValues[step],StringComparer.Ordinal);}
public bool Completed(string step){RequireActive();return savedValues.ContainsKey(step)||adoptedValues.ContainsKey(step);}
public bool Adopted(string step){RequireActive();return adoptedValues.ContainsKey(step);}
public Dictionary<string,string> Recorded(string step){RequireActive();if(!Completed(step))throw new JournalRefusal("No completed write or read-adoption exists");return new Dictionary<string,string>(savedValues.ContainsKey(step)?savedValues[step]:adoptedValues[step],StringComparer.Ordinal);}
public void Adopt(string step,string method,string route,IReadOnlyDictionary<string,string> saved){RequireActive();var record=new List<string>{"S",step,method,route,JournalProtocol.Fingerprint(saved),saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]});var previous=new Dictionary<string,Dictionary<string,string>>(adoptedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{adoptedValues=previous;}Append(record);Apply(record);}
public Dictionary<string,string> Begin(string step,string method,string route,string requestFingerprint)
{
RequireActive();if(intents.ContainsKey(step))throw new JournalRefusal("Never blindly repeat an existing action");
var key=method=="POST"?Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant():"";
var record=new[]{"I",step,method,route,requestFingerprint,key};var previous=new Dictionary<string,Dictionary<string,string>>(intents,StringComparer.Ordinal);try{Apply(record);}finally{intents=previous;}
Append(record);Apply(record);return new Dictionary<string,string>(intents[step],StringComparer.Ordinal);
}
public void Acknowledge(string step,IReadOnlyDictionary<string,string> saved)
{
RequireActive();var record=new List<string>{"A",step,saved.Count.ToString(CultureInfo.InvariantCulture)};foreach(var name in saved.Keys.OrderBy(name=>name,StringComparer.Ordinal))record.AddRange(new[]{name,saved[name]});
var previous=new Dictionary<string,Dictionary<string,string>>(savedValues,StringComparer.Ordinal);try{Apply(record);JournalProtocol.Strings(record);}finally{savedValues=previous;}
Append(record);Apply(record);
}
public void Dispose()
{
if(!owned)return;if(tainted){lockStream.Dispose();lockStream=null;owned=false;return;}
try{RequireActive();}catch{lockStream.Dispose();lockStream=null;owned=false;throw;}
lockStream.Dispose();lockStream=null;owned=false;File.Delete(lockPath);
}
}
static Dictionary<string,string> JournalValues(JsonNode value)
{
if(value is not JsonObject fields)throw new JournalRefusal("Saved/fingerprint values need an explicit object");
var result=new Dictionary<string,string>(StringComparer.Ordinal);
foreach(var field in fields){if(field.Value is not JsonValue item || !item.TryGetValue<string>(out var text) || text==null)throw new JournalRefusal("Saved/fingerprint values must be exact strings");result.Add(field.Key,text);}return result;
}
static JsonObject JournalObject(IReadOnlyDictionary<string,string> fields){var result=new JsonObject();foreach(var field in fields)result.Add(field.Key,JsonValue.Create(field.Value));return result;}
static void JournalAcknowledge(Journal job,string step,JsonNode saved)=>job.Acknowledge(step,JournalValues(saved));
static bool JournalAcknowledged(Journal job,string step)=>job.Acknowledged(step);
static void JournalAdopt(Journal job,string step,string method,string path,JsonNode saved)=>job.Adopt(step,method,path,JournalValues(saved));
static JsonNode JournalBegin(Journal job,string step,string method,string path,string requestFingerprint)=>JournalObject(job.Begin(step,method,path,requestFingerprint));
static bool JournalCompleted(Journal job,string step)=>job.Completed(step);
static string JournalFingerprint(JsonNode value)=>JournalProtocol.Fingerprint(JournalValues(value));
static JsonObject JournalRecorded(Journal job,string step)=>JournalObject(job.Recorded(step));
static bool NotValue(bool value) => !value;
static Journal OpenJournal(string path,string apiBase,string workspace,string slug,string job,string inputFingerprint,JsonNode manifest,string mode)
{
if(manifest is not JsonArray rows)throw new JournalRefusal("A closed write manifest is required");var writes=new List<(string,string,string)>();
foreach(var row in rows){if(row is not JsonArray fields || fields.Count!=3)throw new JournalRefusal("Each write must bind its step/method/path");var values=fields.Select(value=>value is JsonValue item&&item.TryGetValue<string>(out var text)&&text!=null?text:throw new JournalRefusal("Manifest values are exact strings")).ToArray();writes.Add((values[0],values[1],values[2]));}
return new Journal(path,apiBase,workspace,slug,job,inputFingerprint,writes,mode);
}
static string Optional(string name,string fallback) { var value=Environment.GetEnvironmentVariable(name);return value==null||value==""?fallback:value; }
static string PageSize(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!int.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var limit)||limit<=0)throw new Exception("Page size must be a positive int32");return value; }
static JsonNode ParseJson(string value){
using var document=System.Text.Json.JsonDocument.Parse(value);
void Check(System.Text.Json.JsonElement node){
if(node.ValueKind==System.Text.Json.JsonValueKind.Object){var names=new HashSet<string>(StringComparer.Ordinal);foreach(var field in node.EnumerateObject()){if(!names.Add(field.Name))throw new Exception("Duplicate JSON input property");Check(field.Value);}}
else if(node.ValueKind==System.Text.Json.JsonValueKind.Array)foreach(var item in node.EnumerateArray())Check(item);
}
Check(document.RootElement);return JsonNode.Parse(value);
}
static string PositiveId(string value) { if(string.IsNullOrEmpty(value)||value[0]=='0'||!value.All(c=>c>='0'&&c<='9')||!long.TryParse(value,NumberStyles.None,CultureInfo.InvariantCulture,out var id)||id<=0)throw new Exception("Use a positive record ID");return value; }
static void PrintValue(object value) => Console.WriteLine(value is string text ? text : JsonSerializer.Serialize(value));
static void RequireCondition(bool value,string message) { if(!value)throw new Exception(message); }
static string ResponseStatus(Result value)=>value.Status.ToString(CultureInfo.InvariantCulture);
static JsonNode Single(JsonNode value){var rows=Items(value);if(rows.Count!=1)throw new Exception("Expected exactly one selected record");return rows[0];}
static string Text(object value) => value==null?"":value is JsonNode node?Text(node):Convert.ToString(value,CultureInfo.InvariantCulture);
static void ValidateCrmEventInputs(string key, string name, string start, string end)
{
void TextInput(string value, string label, int limit)
{
JournalProtocol.Strings(new[] { value });
if (value.Length == 0 || value != value.Trim())
throw new JournalRefusal("Remove whitespace at the start or end of " + label);
if (value.Length > limit)
throw new JournalRefusal(label + " exceeds " + limit + " UTF-16 code units");
}
void DateInput(string value, string label)
{
if (!DateTime.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
|| value != date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) || date.Year < 1753)
throw new JournalRefusal(label + " must be a calendar date in YYYY-MM-DD on or after 1753-01-01");
}
TextInput(name, "EXHIBITDAY_EVENT_NAME", 500);
TextInput(key, "EXHIBITDAY_EXTERNAL_EVENT_KEY", 3000);
if (name.IndexOfAny(new[] { '<', '>', '\r', '\n' }) >= 0 || name.Equals("null", StringComparison.OrdinalIgnoreCase))
throw new JournalRefusal("Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null");
DateInput(start, "EXHIBITDAY_START_DATE");
DateInput(end, "EXHIBITDAY_END_DATE");
if (string.CompareOrdinal(end, start) < 0)
throw new JournalRefusal("EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE");
}
internal static async Task Run()
{
var external_event_key = Required("EXHIBITDAY_EXTERNAL_EVENT_KEY");
var desired_event_name = Required("EXHIBITDAY_EVENT_NAME");
var desired_start_date = Required("EXHIBITDAY_START_DATE");
var desired_end_date = Required("EXHIBITDAY_END_DATE");
var desired_dates_json = Required("EXHIBITDAY_EXHIBIT_DATES_JSON");
var desired_section_name = Optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning");
var setup_page_size = PageSize(Optional("EXHIBITDAY_PAGE_SIZE", "100"));
var desired_setup_dates = Items(ParseJson(desired_dates_json));
ValidateCrmEventInputs(external_event_key, desired_event_name, desired_start_date, desired_end_date);
var journal_path = Required("EXHIBITDAY_JOURNAL");
var stable_job_id = Required("EXHIBITDAY_JOB_ID");
var job_mode = Optional("EXHIBITDAY_JOB_MODE", "resume");
var setup_workspace_response = await Call("workspace_binding", new JsonObject { }, null, null);
RequireCondition(Equal(ResponseStatus(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var setup_workspace = setup_workspace_response.Body;
var owned_workspace_id = PositiveId(Text(Field(setup_workspace, "id")));
var setup_input_fingerprint = JournalFingerprint(new JsonObject { ["workflow_contract_sha256"] = "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", ["external_event_key"] = external_event_key, ["name"] = desired_event_name, ["start_date"] = desired_start_date, ["end_date"] = desired_end_date, ["section_name"] = desired_section_name, ["dates"] = desired_dates_json });
using (var setup_job = OpenJournal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, new JsonArray(new JsonArray("create_event", "POST", "/v1/events"), new JsonArray("update_event", "PATCH", "/v1/events"), new JsonArray("create_section", "POST", "/v1/tasks/sections"), new JsonArray("save_dates", "PATCH", "/v1/events/dates")), job_mode)) {
var setup_event_id = "";
var setup_section_id = "";
var recorded_section_name = desired_section_name;
if (JournalCompleted(setup_job, "create_event")) {
var recorded_event = JournalRecorded(setup_job, "create_event");
setup_event_id = PositiveId(Text(Field(recorded_event, "id")));
RequireCondition(Equal(Text(Field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.");
} else {
var event_search_offset = "0";
var event_search_query = new JsonObject { ["filter_by_integration_metadata_field_1"] = external_event_key, ["$limit"] = setup_page_size };
while (true) {
event_search_query["$offset"] = event_search_offset;
var event_search_response = await Call("find_existing", event_search_query, null, null);
RequireCondition(Equal(ResponseStatus(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var event_search_page = event_search_response.Body;
var event_search_rows = Items(Field(event_search_page, "list_data"));
RequireCondition(Equal(Text(Field(event_search_page, "records_found")), Text(Count(event_search_rows))), "records_found differs from this complete page's rows.");
RequireCondition(IsPresent(Text(Field(event_search_page, "total_records"))), "The search wrapper needs total_records.");
RequireCondition(Either(Equal(Field(event_search_page, "has_more"), true), Equal(Field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value.");
foreach (var event_search_row in Items(event_search_rows)) {
if (Equal(Text(Field(event_search_row, "integration_metadata_field_1")), external_event_key)) {
var event_search_candidate_id = PositiveId(Text(Field(event_search_row, "id")));
if (IsPresent(setup_event_id)) {
RequireCondition(Equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.");
}
setup_event_id = event_search_candidate_id;
}
}
if (Equal(Field(event_search_page, "has_more"), false)) {
break;
}
RequireCondition(NotValue(IsEmpty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.");
event_search_offset = AddOffset(event_search_offset, Count(event_search_rows));
}
if (NotValue(IsPresent(setup_event_id))) {
var event_write_fingerprint = JournalFingerprint(new JsonObject { ["name"] = desired_event_name, ["start_date"] = desired_start_date, ["end_date"] = desired_end_date, ["integration_metadata_field_1"] = external_event_key });
var event_intent = JournalBegin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint);
var event_create_response = await Call("create_event", new JsonObject { }, new JsonObject { ["name"] = desired_event_name, ["start_date"] = desired_start_date, ["end_date"] = desired_end_date, ["integration_metadata_field_1"] = external_event_key }, Text(Field(event_intent, "idempotency_key")));
RequireCondition(Equal(ResponseStatus(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var created_event = event_create_response.Body;
setup_event_id = PositiveId(Text(Field(created_event, "id")));
RequireCondition(Equal(Text(Field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.");
RequireCondition(Both(IsPresent(Text(Field(created_event, "name"))), Both(IsPresent(Text(Field(created_event, "start_date"))), IsPresent(Text(Field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.");
JournalAcknowledge(setup_job, "create_event", new JsonObject { ["id"] = setup_event_id, ["integration_metadata_field_1"] = external_event_key });
}
}
var event_confirmation_response = await Call("confirm_event", new JsonObject { ["id"] = setup_event_id, ["$include_record_revision"] = "true" }, null, null);
RequireCondition(Equal(ResponseStatus(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var confirmed_setup_event = event_confirmation_response.Body;
RequireCondition(Both(Equal(Text(Field(confirmed_setup_event, "id")), setup_event_id), Equal(Text(Field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.");
if (NotValue(JournalCompleted(setup_job, "create_event"))) {
JournalAdopt(setup_job, "create_event", "GET", "/v1/events/info", new JsonObject { ["id"] = Text(Field(confirmed_setup_event, "id")), ["integration_metadata_field_1"] = Text(Field(confirmed_setup_event, "integration_metadata_field_1")) });
}
var setup_event_revision = Text(Field(confirmed_setup_event, "record_revision"));
RequireCondition(IsPresent(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.");
RequireCondition(Both(Both(IsPresent(Text(Field(confirmed_setup_event, "name"))), IsPresent(Text(Field(confirmed_setup_event, "start_date")))), IsPresent(Text(Field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.");
if (JournalCompleted(setup_job, "update_event")) {
var recorded_event_update = JournalRecorded(setup_job, "update_event");
RequireCondition(Both(Equal(Text(Field(recorded_event_update, "id")), setup_event_id), Equal(Text(Field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.");
RequireCondition(Both(Both(Equal(Text(Field(confirmed_setup_event, "name")), desired_event_name), Equal(Text(Field(confirmed_setup_event, "start_date")), desired_start_date)), Equal(Text(Field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.");
} else {
if (Both(Both(Equal(Text(Field(confirmed_setup_event, "name")), desired_event_name), Equal(Text(Field(confirmed_setup_event, "start_date")), desired_start_date)), Equal(Text(Field(confirmed_setup_event, "end_date")), desired_end_date))) {
JournalAdopt(setup_job, "update_event", "GET", "/v1/events/info", new JsonObject { ["id"] = setup_event_id, ["integration_metadata_field_1"] = external_event_key });
} else {
RequireCondition(NotValue(JournalAcknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.");
var event_update_body = new JsonObject { ["id"] = setup_event_id, ["expected_revision"] = setup_event_revision };
if (NotValue(Equal(Text(Field(confirmed_setup_event, "name")), desired_event_name))) {
event_update_body["name"] = desired_event_name;
}
if (NotValue(Equal(Text(Field(confirmed_setup_event, "start_date")), desired_start_date))) {
event_update_body["start_date"] = desired_start_date;
}
if (NotValue(Equal(Text(Field(confirmed_setup_event, "end_date")), desired_end_date))) {
event_update_body["end_date"] = desired_end_date;
}
var event_update_fingerprint = JournalFingerprint(event_update_body);
JournalBegin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint);
var event_update_response = await Call("update_event", new JsonObject { }, event_update_body, null);
RequireCondition(Equal(ResponseStatus(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var event_update_ack = event_update_response.Body;
var event_updated_revision = Text(Field(event_update_ack, "record_revision"));
RequireCondition(IsPresent(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.");
JournalAcknowledge(setup_job, "update_event", new JsonObject { ["id"] = setup_event_id, ["integration_metadata_field_1"] = external_event_key, ["record_revision"] = event_updated_revision });
}
}
var event_update_verify_response = await Call("verify_event_update", new JsonObject { ["id"] = setup_event_id }, null, null);
RequireCondition(Equal(ResponseStatus(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var verified_setup_event = event_update_verify_response.Body;
RequireCondition(Both(Both(Equal(Text(Field(verified_setup_event, "id")), setup_event_id), Equal(Text(Field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), Both(Both(Equal(Text(Field(verified_setup_event, "name")), desired_event_name), Equal(Text(Field(verified_setup_event, "start_date")), desired_start_date)), Equal(Text(Field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.");
if (JournalCompleted(setup_job, "create_section")) {
var recorded_section = JournalRecorded(setup_job, "create_section");
setup_section_id = PositiveId(Text(Field(recorded_section, "id")));
RequireCondition(Equal(Text(Field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.");
recorded_section_name = Text(Field(recorded_section, "name"));
} else {
var section_search_offset = "0";
var section_search_query = new JsonObject { ["filter_by_event_id"] = setup_event_id, ["$limit"] = setup_page_size };
while (true) {
section_search_query["$offset"] = section_search_offset;
var section_search_response = await Call("find_section", section_search_query, null, null);
RequireCondition(Equal(ResponseStatus(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var section_search_page = section_search_response.Body;
var section_search_rows = Items(Field(section_search_page, "list_data"));
RequireCondition(Equal(Text(Field(section_search_page, "records_found")), Text(Count(section_search_rows))), "records_found differs from this complete page's rows.");
RequireCondition(IsPresent(Text(Field(section_search_page, "total_records"))), "The search wrapper needs total_records.");
RequireCondition(Either(Equal(Field(section_search_page, "has_more"), true), Equal(Field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value.");
foreach (var section_search_row in Items(section_search_rows)) {
RequireCondition(Equal(Text(Field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.");
if (Equal(Text(Field(section_search_row, "name")), desired_section_name)) {
var section_search_candidate_id = PositiveId(Text(Field(section_search_row, "id")));
if (IsPresent(setup_section_id)) {
RequireCondition(Equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.");
}
setup_section_id = section_search_candidate_id;
}
}
if (Equal(Field(section_search_page, "has_more"), false)) {
break;
}
RequireCondition(NotValue(IsEmpty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.");
section_search_offset = AddOffset(section_search_offset, Count(section_search_rows));
}
if (NotValue(IsPresent(setup_section_id))) {
var section_write_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = setup_event_id, ["name"] = desired_section_name });
var section_intent = JournalBegin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint);
var section_create_response = await Call("create_section", new JsonObject { }, new JsonObject { ["event_id"] = setup_event_id, ["name"] = desired_section_name }, Text(Field(section_intent, "idempotency_key")));
RequireCondition(Equal(ResponseStatus(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var created_section = section_create_response.Body;
setup_section_id = PositiveId(Text(Field(created_section, "id")));
RequireCondition(Equal(Text(Field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.");
recorded_section_name = Text(Field(created_section, "name"));
RequireCondition(IsPresent(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.");
JournalAcknowledge(setup_job, "create_section", new JsonObject { ["id"] = setup_section_id, ["event_id"] = setup_event_id, ["name"] = recorded_section_name });
}
}
var section_confirmation_response = await Call("confirm_section", new JsonObject { ["id"] = setup_section_id }, null, null);
RequireCondition(Equal(ResponseStatus(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var confirmed_setup_section = section_confirmation_response.Body;
RequireCondition(Both(Equal(Text(Field(confirmed_setup_section, "id")), setup_section_id), Both(Equal(Text(Field(confirmed_setup_section, "event_id")), setup_event_id), Equal(Text(Field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.");
if (NotValue(JournalCompleted(setup_job, "create_section"))) {
JournalAdopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", new JsonObject { ["event_id"] = Text(Field(confirmed_setup_section, "event_id")), ["id"] = Text(Field(confirmed_setup_section, "id")), ["name"] = Text(Field(confirmed_setup_section, "name")) });
}
var setup_dates_response = await Call("read_dates", new JsonObject { ["event_id"] = setup_event_id, ["filter_by_date_type_id"] = "1", ["$include_record_revision"] = "true" }, null, null);
RequireCondition(Equal(ResponseStatus(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var setup_dates_page = setup_dates_response.Body;
RequireCondition(Both(Equal(Text(Field(setup_dates_page, "records_found")), "1"), Both(Equal(Text(Field(setup_dates_page, "total_records")), "1"), Equal(Field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.");
var setup_dates_group = Single(Field(setup_dates_page, "list_data"));
RequireCondition(Both(Equal(Text(Field(setup_dates_group, "event_id")), setup_event_id), Equal(Text(Field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.");
var setup_dates_revision = Text(Field(setup_dates_group, "record_revision"));
RequireCondition(IsPresent(setup_dates_revision), "Read the actual selected group revision before replacing it.");
if (JournalCompleted(setup_job, "save_dates")) {
var recorded_dates = JournalRecorded(setup_job, "save_dates");
RequireCondition(Both(Equal(Text(Field(recorded_dates, "event_id")), setup_event_id), Equal(Text(Field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.");
} else {
var setup_dates_fingerprint = JournalFingerprint(new JsonObject { ["event_id"] = setup_event_id, ["date_type_id"] = "1", ["dates"] = desired_dates_json, ["expected_revision"] = setup_dates_revision });
JournalBegin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint);
var setup_dates_save_response = await Call("save_dates", new JsonObject { }, new JsonObject { ["event_id"] = setup_event_id, ["date_type_id"] = "1", ["dates"] = CopyNode(desired_setup_dates), ["expected_revision"] = setup_dates_revision }, null);
RequireCondition(Equal(ResponseStatus(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var setup_dates_ack = setup_dates_save_response.Body;
var setup_dates_saved_revision = Text(Field(setup_dates_ack, "record_revision"));
RequireCondition(IsPresent(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.");
JournalAcknowledge(setup_job, "save_dates", new JsonObject { ["event_id"] = setup_event_id, ["date_type_id"] = "1", ["record_revision"] = setup_dates_saved_revision });
}
var setup_dates_verify_response = await Call("verify_dates", new JsonObject { ["event_id"] = setup_event_id, ["filter_by_date_type_id"] = "1" }, null, null);
RequireCondition(Equal(ResponseStatus(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var setup_dates_verify_page = setup_dates_verify_response.Body;
RequireCondition(Both(Equal(Text(Field(setup_dates_verify_page, "records_found")), "1"), Both(Equal(Text(Field(setup_dates_verify_page, "total_records")), "1"), Equal(Field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.");
var setup_dates_verify_group = Single(Field(setup_dates_verify_page, "list_data"));
RequireCondition(Both(Equal(Text(Field(setup_dates_verify_group, "event_id")), setup_event_id), Equal(Text(Field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.");
RequireCondition(DeepEqual(Field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.");
var setup_event_readback_response = await Call("event_readback", new JsonObject { ["id"] = setup_event_id }, null, null);
RequireCondition(Equal(ResponseStatus(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
var setup_event_readback = setup_event_readback_response.Body;
RequireCondition(Both(Equal(Text(Field(setup_event_readback, "id")), setup_event_id), Equal(Text(Field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.");
RequireCondition(Both(Both(Equal(Text(Field(setup_event_readback, "name")), desired_event_name), Equal(Text(Field(setup_event_readback, "start_date")), desired_start_date)), Equal(Text(Field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.");
var planning_section_present = false;
foreach (var setup_event_section in Items(Items(Field(setup_event_readback, "task_sections")))) {
if (Equal(Text(Field(setup_event_section, "id")), setup_section_id)) {
planning_section_present = true;
}
}
RequireCondition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.");
PrintValue(new JsonObject { ["event_id"] = setup_event_id, ["task_section_id"] = setup_section_id, ["dates_verified"] = "true" });
}
}
static Task Main() => Run();
}
// Java 11+ with Gson on the classpath. Set EXHIBITDAY_API_KEY; save as Main.java.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.*;
import java.util.*;
public class Main {
static final Gson JSON = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER).create();
static final String BASE = "https://api.exhibitday.com/v1";
static final Map<String,Object> SPEC = JSON.fromJson("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}", Map.class);
static final String API_KEY = headerKey(required("EXHIBITDAY_API_KEY"));
static String headerKey(String value){if(value.chars().anyMatch(c->c<32||c>126))throw new IllegalArgumentException("Use the API key as one ASCII header value without control characters");return value;}
static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).followRedirects(HttpClient.Redirect.NEVER).build();
interface RequestSender { HttpResponse<String> send(HttpRequest request)throws IOException,InterruptedException; }
static RequestSender SEND=request->CLIENT.send(request,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
static class Result { int status; Object body; Map<String,String> headers; String raw;
Result(int s, Object b, Map<String,String> h,String r) {status=s;body=b;headers=h;raw=r;} }
// An API error response. Branch on errorCode (and status), never on the message text.
// uncertain is true when a PATCH or DELETE got no response or a server error: it may or may not have been applied.
static class ApiException extends IllegalStateException { final int status; final String errorCode; final boolean uncertain;
ApiException(int status,Object errorCode,String message) {this(status,errorCode,message,false);}
ApiException(int status,Object errorCode,String message,boolean uncertain) {super(message);this.status=status;this.errorCode=errorCode==null?null:String.valueOf(errorCode);this.uncertain=uncertain;} }
static String required(String name) {String value=System.getenv(name);if(value==null||value.trim().isEmpty())throw new IllegalArgumentException("Set "+name);return value;}
static String env(String name,String fallback) {String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;}
static String text(Object value) {return value==null?"":value.toString();}
@SuppressWarnings("unchecked") static Map<String,Object> obj(Object value) {return value==null?new LinkedHashMap<>(): (Map<String,Object>)value;}
@SuppressWarnings("unchecked") static List<Object> list(Object value) {return value==null?Collections.emptyList():(List<Object>)value;}
static Map<String,Object> map(Object... pairs) {Map<String,Object> result=new LinkedHashMap<>();for(int i=0;i<pairs.length;i+=2)result.put((String)pairs[i],pairs[i+1]);return result;}
static void pause(double seconds) {try {Thread.sleep((long)(Math.max(0,seconds)*1000));}catch(InterruptedException error){Thread.currentThread().interrupt();throw new RuntimeException(error);}}
static Result call(String name,Map<String,Object> query,Object body,String key) {
Map<String,Object> route=obj(obj(SPEC.get("requests")).get(name));String method=text(route.get("method"));
Map<String,Object> headers=map("Authorization","Bearer " + API_KEY,"Accept","application/json");
if(method.equals("POST")){if(key==null||key.isEmpty())throw new IllegalArgumentException("Persist a logical create key before sending POST");headers.put("Idempotency-Key",key);}
String data=body==null?null:JSON.toJson(body);if(data!=null)headers.put("Content-Type","application/json");
StringJoiner queryString=new StringJoiner("&");
if(query!=null)query.forEach((k,v)->queryString.add(URLEncoder.encode(k,StandardCharsets.UTF_8)+"="+URLEncoder.encode(text(v),StandardCharsets.UTF_8)));
String url=BASE+text(route.get("path"))+(queryString.length()==0?"":"?"+queryString);
// Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
// server error is never resent blindly: it may already have been applied, so the caller reads the record first.
boolean resend=method.equals("GET");
for(int attempt=0;attempt<5;attempt++) {
HttpRequest.Builder request=HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(30));
headers.forEach((k,v)->request.header(k,text(v)));
request.method(method,data==null?HttpRequest.BodyPublishers.noBody():HttpRequest.BodyPublishers.ofString(data,StandardCharsets.UTF_8));
HttpResponse<String> response;
try {response=SEND.send(request.build());}
catch(InterruptedException error){Thread.currentThread().interrupt();throw new RuntimeException(error);}
catch(IOException error){if(!resend)throw new ApiException(0,null,"No response",true);if(attempt==4)throw new RuntimeException(error);pause(Math.pow(2,attempt));continue;}
int status=response.statusCode();Object parsed=null;
if(status!=304&&!response.body().isEmpty()) {
try {parsed=JSON.fromJson(response.body(),Object.class);}
catch(RuntimeException error){if(status<400)throw new IllegalStateException("Expected a JSON success response",error);}
}
Map<String,String> responseHeaders=new HashMap<>();response.headers().map().forEach((k,v)->responseHeaders.put(k.toLowerCase(Locale.ROOT),String.join(", ",v)));
if(status>=500&&!resend)throw new ApiException(status,obj(parsed).get("error_code"),"HTTP "+status,true);
boolean retry=resend&&(status==429||status>=500);
if(retry) {
if(attempt==4)throw new IllegalStateException("Retry limit reached; check the outcome before starting a new create");
double seconds=Math.pow(2,attempt);
try {double value=Double.parseDouble(responseHeaders.get("retry-after"));if(Double.isFinite(value)&&value>=0)seconds=value;}catch(Exception ignored){}
pause(seconds);continue;
}
if(status>=400)throw new ApiException(status,obj(parsed).get("error_code"),"HTTP "+status+": "+obj(parsed).get("error_code")+" (request "+obj(parsed).get("request_id")+")");
return new Result(status,parsed,responseHeaders,response.body());
}
throw new IllegalStateException("Retry limit reached");
}
static String add_offset(String offset,long received){long result=Math.addExact(Long.parseLong(offset),received);if(received<=0||result>Integer.MAX_VALUE)throw new IllegalStateException("Cannot advance this int32 offset; reconcile the query");return Long.toString(result);}
static boolean both(boolean left,boolean right){return left&&right;}
static List<Object> items(Object value){if(!(value instanceof List))throw new IllegalStateException("Expected a JSON array");return list(value);}
static long count(Object value){return items(value).size();}
static boolean deep_equal(Object left,Object right){return Objects.equals(left,right);}
static boolean either(boolean left,boolean right){return left||right;}
static boolean equal(Object left,Object right){return Objects.equals(left,right);}
static Object field(Object value,String name){if(!(value instanceof Map)||!obj(value).containsKey(name))throw new IllegalStateException("Missing response field: "+name);return obj(value).get(name);}
static boolean is_empty(Object value){return count(value)==0;}
static boolean is_present(String value){return value!=null&&!value.isEmpty();}
// Private client restart state only. No transport, application or JSON interpreter.
static final class Journal implements AutoCloseable {
public static final class Refusal extends IllegalStateException { Refusal(String message){super(message);} }
public static final byte[] PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".getBytes(StandardCharsets.US_ASCII);
static boolean valid(String value,String pattern){return value!=null&&value.matches(pattern);}
static byte[] utf8(String value)throws java.nio.charset.CharacterCodingException {
if(value==null)throw new Refusal("Journal fields are exact strings");
java.nio.ByteBuffer encoded=StandardCharsets.UTF_8.newEncoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).encode(java.nio.CharBuffer.wrap(value));byte[] raw=new byte[encoded.remaining()];encoded.get(raw);return raw;
}
static String ascii(byte[] raw,int start,int count){for(int i=start;i<start+count;i++)if((raw[i]&255)>127)throw new Refusal("Journal framing must be canonical ASCII");return new String(raw,start,count,StandardCharsets.US_ASCII);}
public static byte[] strings(Collection<String> values)throws IOException {
ByteArrayOutputStream output=new ByteArrayOutputStream();for(String value:values){byte[] raw=utf8(value);output.write((raw.length+":").getBytes(StandardCharsets.US_ASCII));output.write(raw);}return output.toByteArray();
}
static int find(byte[] raw,int offset,int value){for(int i=offset;i<raw.length;i++)if((raw[i]&255)==value)return i;return-1;}
public static List<String> readStrings(byte[] raw)throws IOException {
List<String> values=new ArrayList<>();int offset=0;
while(offset<raw.length){int end=find(raw,offset,58);if(end<0)throw new Refusal("Incomplete journal string length");String text=ascii(raw,offset,end-offset);
if(!valid(text,"0|[1-9][0-9]*"))throw new Refusal("Noncanonical journal string length");java.math.BigInteger size=new java.math.BigInteger(text);offset=end+1;if(size.compareTo(java.math.BigInteger.valueOf(raw.length-offset))>0)throw new Refusal("Incomplete journal string");int count=size.intValueExact();
values.add(StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(raw,offset,count)).toString());offset+=count;}
return values;
}
public static String digest(byte[] raw){try{byte[] hash=java.security.MessageDigest.getInstance("SHA-256").digest(raw);StringBuilder text=new StringBuilder();for(byte item:hash)text.append(String.format(Locale.ROOT,"%02X",item&255));return text.toString();}catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}}
public static String fingerprint(Map<String,String> pairs)throws IOException {
List<String> values=new ArrayList<>();for(String name:new TreeSet<>(pairs.keySet())){if(!valid(name,"[A-Za-z0-9_.-]+")||Arrays.asList("api_key","exhibitday_api_key").contains(name.toLowerCase(Locale.ROOT)))throw new Refusal("Use explicit secret-free fingerprint names");values.add(name);values.add(pairs.get(name));}return digest(strings(values));
}
public static byte[] frame(Collection<String> values)throws IOException {byte[] payload=strings(values);ByteArrayOutputStream output=new ByteArrayOutputStream();output.write((payload.length+" "+digest(payload)+"\n").getBytes(StandardCharsets.US_ASCII));output.write(payload);output.write(10);return output.toByteArray();}
public static List<List<String>> decode(byte[] raw)throws IOException {
if(raw.length<PREAMBLE.length||!Arrays.equals(Arrays.copyOfRange(raw,0,PREAMBLE.length),PREAMBLE))throw new Refusal("Unknown or incomplete journal version");int offset=PREAMBLE.length;List<List<String>> records=new ArrayList<>();
while(offset<raw.length){int end=find(raw,offset,10);if(end<0)throw new Refusal("Incomplete frame header; reconcile before retry");String header=ascii(raw,offset,end-offset);
if(!valid(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"))throw new Refusal("Invalid frame header");String[] fields=header.split(" ");java.math.BigInteger size=new java.math.BigInteger(fields[0]);offset=end+1;
if(size.compareTo(java.math.BigInteger.valueOf(raw.length-offset))>=0)throw new Refusal("Incomplete frame; reconcile before retry");int count=size.intValueExact();byte[] payload=Arrays.copyOfRange(raw,offset,offset+count);offset+=count;
if(raw[offset]!=10||!digest(payload).equals(fields[1]))throw new Refusal("Journal integrity failed; reconcile before retry");records.add(readStrings(payload));offset++;}return records;
}
static void writeAll(java.nio.channels.FileChannel target,byte[] raw)throws IOException {java.nio.ByteBuffer data=java.nio.ByteBuffer.wrap(raw);while(data.hasRemaining())if(target.write(data)<=0)throw new IOException("Journal write did not advance");}
static java.nio.channels.FileChannel createPrivate(Path path,OpenOption... options)throws IOException {
java.nio.file.attribute.FileAttribute<?>[] attributes=FileSystems.getDefault().supportedFileAttributeViews().contains("posix")?new java.nio.file.attribute.FileAttribute<?>[]{java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"))}:new java.nio.file.attribute.FileAttribute<?>[0];
return java.nio.channels.FileChannel.open(path,new HashSet<>(Arrays.asList(options)),attributes);
}
final Path path,lockPath;final String owner;final List<String> header;
final Map<String,List<String>> allowed=new LinkedHashMap<>();Map<String,Map<String,String>> intents=new LinkedHashMap<>(),savedValues=new LinkedHashMap<>();
Map<String,Map<String,String>> adoptedValues=new LinkedHashMap<>();
java.nio.channels.FileChannel lock;boolean owned,tainted;Object fileKey;java.nio.file.attribute.FileTime creation;
public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List<List<String>> writes)throws IOException {this(path,apiBase,workspace,slug,job,inputFingerprint,writes,"resume");}
public Journal(Path path,String apiBase,String workspace,String slug,String job,String inputFingerprint,List<List<String>> writes,String mode)throws IOException {
this.path=path;lockPath=Path.of(path.toString()+".lock");byte[] random=new byte[16];new java.security.SecureRandom().nextBytes(random);StringBuilder token=new StringBuilder();for(byte item:random)token.append(String.format(Locale.ROOT,"%02x",item&255));owner=token.toString();
URI address=URI.create(apiBase);if(!Arrays.asList("https","http").contains(address.getScheme())||address.getHost()==null||address.getUserInfo()!=null||address.getRawQuery()!=null||address.getRawFragment()!=null||!valid(slug,"[a-z][a-z0-9-]*"))throw new Refusal("Use actual API base and closed guide slug");
if(job==null||job.trim().isEmpty()||!valid(workspace,"[1-9][0-9]*")||!valid(inputFingerprint,"[0-9A-F]{64}"))throw new Refusal("Use actual workspace, stable explicit job ID and exact fingerprint");
if(!Arrays.asList("new","resume").contains(mode))throw new Refusal("Choose new or resume for this local job");
List<String> manifest=new ArrayList<>();for(List<String> item:writes){if(item.size()!=3)throw new Refusal("Invalid write manifest shape");String step=item.get(0),method=item.get(1),route=item.get(2);
if(!valid(step,"[a-z][a-z0-9_-]*")||allowed.containsKey(step)||!Arrays.asList("POST","PATCH","DELETE").contains(method)||!valid(route,"/v1/[A-Za-z0-9_/-]+")||route.contains("//"))throw new Refusal("Use a closed unique write manifest");allowed.put(step,List.of(method,route));manifest.addAll(item);}
if(allowed.isEmpty())throw new Refusal("Only write workflows need a restart journal");header=List.of("H","1",apiBase,workspace,slug,job,inputFingerprint,digest(strings(manifest)));strings(header);
try{lock=createPrivate(lockPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);owned=true;}catch(FileAlreadyExistsException error){throw new Refusal("This journal is locked; do not overlap jobs or steal a stale lock");}
try{writeAll(lock,owner.getBytes(StandardCharsets.US_ASCII));lock.force(true);java.nio.file.attribute.BasicFileAttributes identity=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);fileKey=identity.fileKey();creation=identity.creationTime();
if(Files.isSymbolicLink(path))throw new Refusal("Choose a private regular journal file");
if(mode.equals("resume")&&!Files.exists(path))throw new Refusal("Journal missing: stop and reconcile lost state before starting a new logical job");
if(mode.equals("new")&&Files.exists(path))throw new Refusal("Journal exists; use resume for the same logical job");
if(mode.equals("new")){try(java.nio.channels.FileChannel target=createPrivate(path,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){writeAll(target,PREAMBLE);writeAll(target,frame(header));target.force(true);}}
List<List<String>> records=decode(Files.readAllBytes(path));if(records.isEmpty()||!records.get(0).equals(header))throw new Refusal("Journal workspace/base/guide/job/input binding differs");for(List<String> record:records.subList(1,records.size()))apply(record);
if(intents.keySet().stream().anyMatch(step->!savedValues.containsKey(step)))throw new Refusal("Saved intent lacks ACK; stop and reconcile before retry");
}catch(IOException|RuntimeException error){close();throw error;}
}
void apply(List<String> record)throws IOException {
if(record.isEmpty())throw new Refusal("Empty journal record");
if(record.get(0).equals("I")){
if(record.size()!=6)throw new Refusal("Invalid intent shape");String step=record.get(1),method=record.get(2),route=record.get(3),fingerprint=record.get(4),key=record.get(5);
if(!valid(step,"[a-z][a-z0-9_-]*")||intents.containsKey(step)||adoptedValues.containsKey(step)||!List.of(method,route).equals(allowed.get(step))||!valid(fingerprint,"[0-9A-F]{64}")||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Invalid, future or repeated intent");
if(method.equals("POST")&&!valid(key,"[0-9a-f]{32}")||!method.equals("POST")&&!key.isEmpty())throw new Refusal("Invalid persisted action key");intents.put(step,new LinkedHashMap<>(Map.of("method",method,"path",route,"request_fingerprint",fingerprint,"idempotency_key",key)));
}else if(record.get(0).equals("A")){
if(record.size()<3||!valid(record.get(2),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(2)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-3))||!intents.containsKey(record.get(1))||savedValues.containsKey(record.get(1)))throw new Refusal("ACK without exactly one prior intent");
List<String> names=new ArrayList<>();for(int i=3;i<record.size();i+=2)names.add(record.get(i));if(!names.equals(new ArrayList<>(new TreeSet<>(names)))||names.stream().anyMatch(name->!valid(name,"[a-z][a-z0-9_]*")||name.equals("api_key")||name.equals("exhibitday_api_key")))throw new Refusal("ACK fields must be unique sorted secret-free identifiers");
Map<String,String> saved=new LinkedHashMap<>();for(int i=0;i<names.size();i++)saved.put(names.get(i),record.get(4+2*i));savedValues.put(record.get(1),saved);
}else if(record.get(0).equals("S")){
if(record.size()<6)throw new Refusal("Invalid read-adoption shape");String step=record.get(1),method=record.get(2),route=record.get(3),readFingerprint=record.get(4);
Set<String> completed=new HashSet<>(savedValues.keySet());completed.addAll(adoptedValues.keySet());List<String> order=new ArrayList<>(allowed.keySet());
if(completed.size()>=order.size()||!completed.equals(new HashSet<>(order.subList(0,completed.size())))||!step.equals(order.get(completed.size()))||intents.keySet().stream().anyMatch(name->!savedValues.containsKey(name)))throw new Refusal("Adopt only the exact next setup action without any pending intent");
List<String> target=allowed.get(step);String expected=(List.of("POST","/v1/events").equals(target)||step.equals("update_event")&&List.of("PATCH","/v1/events").equals(target))?"/v1/events/info":List.of("POST","/v1/tasks/sections").equals(target)?"/v1/tasks/sections/info":null;
if(!method.equals("GET")||expected==null||!route.equals(expected))throw new Refusal("Adoption requires the exact source-bound single Event or section read");
if(!valid(record.get(5),"0|[1-9][0-9]*")||!new java.math.BigInteger(record.get(5)).multiply(java.math.BigInteger.TWO).equals(java.math.BigInteger.valueOf(record.size()-6)))throw new Refusal("Invalid read-adoption field count");
List<String> names=new ArrayList<>();for(int i=6;i<record.size();i+=2)names.add(record.get(i));List<String> fields=expected.equals("/v1/events/info")?List.of("id","integration_metadata_field_1"):List.of("event_id","id","name");if(!names.equals(fields))throw new Refusal("Read-adoption fields must match the exact source tuple");
Map<String,String> saved=new LinkedHashMap<>();for(int i=0;i<names.size();i++)saved.put(names.get(i),record.get(7+2*i));
for(String name:List.of("id","event_id"))if(saved.containsKey(name)&&(!valid(saved.get(name),"[1-9][0-9]*")||new java.math.BigInteger(saved.get(name)).compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE))>0))throw new Refusal("Read-adoption IDs must be exact positive Int64 strings");
if(fields.stream().anyMatch(name->!List.of("id","event_id").contains(name)&&saved.get(name).isEmpty())||!readFingerprint.equals(fingerprint(saved)))throw new Refusal("Read-adoption material must be complete and fingerprint-bound");adoptedValues.put(step,saved);
}else throw new Refusal("Unknown journal transition");
}
void requireActive()throws IOException {
if(!owned||lock==null||tainted)throw new Refusal("Journal is closed or IO outcome needs reconciliation");java.nio.file.attribute.BasicFileAttributes current=Files.readAttributes(lockPath,java.nio.file.attribute.BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS);
if(!Objects.equals(fileKey,current.fileKey())||!creation.equals(current.creationTime())||!Arrays.equals(Files.readAllBytes(lockPath),owner.getBytes(StandardCharsets.US_ASCII)))throw new Refusal("Journal lock was replaced; stop without deleting it");
}
void append(List<String> record)throws IOException {requireActive();byte[] raw=frame(record);try(java.nio.channels.FileChannel target=java.nio.channels.FileChannel.open(path,StandardOpenOption.WRITE,StandardOpenOption.APPEND)){writeAll(target,raw);target.force(true);}catch(IOException|RuntimeException error){tainted=true;throw error;}}
public boolean acknowledged(String step)throws IOException{requireActive();return savedValues.containsKey(step);}
public Map<String,String> saved(String step)throws IOException{requireActive();if(!savedValues.containsKey(step))throw new Refusal("No acknowledged state exists");return new LinkedHashMap<>(savedValues.get(step));}
public boolean completed(String step)throws IOException{requireActive();return savedValues.containsKey(step)||adoptedValues.containsKey(step);}
public boolean adopted(String step)throws IOException{requireActive();return adoptedValues.containsKey(step);}
public Map<String,String> recorded(String step)throws IOException{requireActive();if(!completed(step))throw new Refusal("No completed write or read-adoption exists");return new LinkedHashMap<>(savedValues.containsKey(step)?savedValues.get(step):adoptedValues.get(step));}
public void adopt(String step,String method,String route,Map<String,String> saved)throws IOException{requireActive();List<String> record=new ArrayList<>(List.of("S",step,method,route,fingerprint(saved),Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));}Map<String,Map<String,String>> previous=new LinkedHashMap<>(adoptedValues);try{apply(record);strings(record);}finally{adoptedValues=previous;}append(record);apply(record);}
public Map<String,String> begin(String step,String method,String route,String requestFingerprint)throws IOException {
requireActive();if(intents.containsKey(step))throw new Refusal("Never blindly repeat an existing action");String key="";if(method.equals("POST")){byte[] bytes=new byte[16];new java.security.SecureRandom().nextBytes(bytes);StringBuilder text=new StringBuilder();for(byte item:bytes)text.append(String.format(Locale.ROOT,"%02x",item&255));key=text.toString();}
List<String> record=List.of("I",step,method,route,requestFingerprint,key);Map<String,Map<String,String>> previous=new LinkedHashMap<>(intents);try{apply(record);}finally{intents=previous;}append(record);apply(record);return new LinkedHashMap<>(intents.get(step));
}
public void acknowledge(String step,Map<String,String> saved)throws IOException {
requireActive();List<String> record=new ArrayList<>(List.of("A",step,Integer.toString(saved.size())));for(String name:new TreeSet<>(saved.keySet())){record.add(name);record.add(saved.get(name));}
Map<String,Map<String,String>> previous=new LinkedHashMap<>(savedValues);try{apply(record);strings(record);}finally{savedValues=previous;}append(record);apply(record);
}
public void close()throws IOException {
if(!owned)return;if(tainted){lock.close();lock=null;owned=false;return;}
try{requireActive();}catch(IOException|RuntimeException error){lock.close();lock=null;owned=false;throw error;}lock.close();lock=null;owned=false;Files.delete(lockPath);
}
}
static Map<String,String> journal_values(Object value){if(!(value instanceof Map))throw new Journal.Refusal("Saved/fingerprint values need an explicit object");Map<String,String> result=new LinkedHashMap<>();for(Map.Entry<?,?> field:((Map<?,?>)value).entrySet()){if(!(field.getKey() instanceof String)||!(field.getValue() instanceof String))throw new Journal.Refusal("Saved/fingerprint values must be exact strings");result.put((String)field.getKey(),(String)field.getValue());}return result;}
static void journal_acknowledge(Journal job,String step,Object saved)throws IOException{job.acknowledge(step,journal_values(saved));}
static boolean journal_acknowledged(Journal job,String step)throws IOException{return job.acknowledged(step);}
static void journal_adopt(Journal job,String step,String method,String path,Object saved)throws IOException{job.adopt(step,method,path,journal_values(saved));}
static Object journal_begin(Journal job,String step,String method,String path,String requestFingerprint)throws IOException{return new LinkedHashMap<String,Object>(job.begin(step,method,path,requestFingerprint));}
static boolean journal_completed(Journal job,String step)throws IOException{return job.completed(step);}
static String journal_fingerprint(Object value)throws IOException{return Journal.fingerprint(journal_values(value));}
static Object journal_recorded(Journal job,String step)throws IOException{return new LinkedHashMap<>(job.recorded(step));}
static boolean not_value(boolean value){return !value;}
static Journal open_journal(String path,String base,String workspace,String slug,String job,String inputFingerprint,Object manifest,String mode)throws IOException {
if(!(manifest instanceof List))throw new Journal.Refusal("A closed write manifest is required");List<List<String>> writes=new ArrayList<>();for(Object row:(List<?>)manifest){if(!(row instanceof List)||((List<?>)row).size()!=3)throw new Journal.Refusal("Each write must bind step/method/path");List<String> fields=new ArrayList<>();for(Object value:(List<?>)row){if(!(value instanceof String))throw new Journal.Refusal("Manifest values are exact strings");fields.add((String)value);}writes.add(fields);}return new Journal(Path.of(path),base,workspace,slug,job,inputFingerprint,writes,mode);
}
static String optional(String name,String fallback){String value=System.getenv(name);return value==null||value.isEmpty()?fallback:value;}
static String page_size(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Integer.parseInt(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Page size must be a positive int32");}}
static Object parse_json(String value){
Object result=new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER).setStrictness(com.google.gson.Strictness.STRICT).create().fromJson(value,Object.class);
java.util.regex.Matcher tokens=java.util.regex.Pattern.compile("\"(?:\\\\.|[^\"\\\\])*\"|[{}\\[\\],]",java.util.regex.Pattern.DOTALL).matcher(value);
List<Map<String,Object>> stack=new ArrayList<>();
while(tokens.find()){
String token=tokens.group();
if(token.equals("{"))stack.add(map("object",true,"key",true,"names",new HashSet<String>()));
else if(token.equals("["))stack.add(map("object",false));
else if(token.equals("}")||token.equals("]"))stack.remove(stack.size()-1);
else if(token.equals(",")){if(!stack.isEmpty()&&Boolean.TRUE.equals(stack.get(stack.size()-1).get("object")))stack.get(stack.size()-1).put("key",true);}
else if(!stack.isEmpty()){
Map<String,Object> frame=stack.get(stack.size()-1);
if(Boolean.TRUE.equals(frame.get("object"))&&Boolean.TRUE.equals(frame.get("key"))){String name=JSON.fromJson(token,String.class);@SuppressWarnings("unchecked") Set<String> names=(Set<String>)frame.get("names");if(!names.add(name))throw new IllegalArgumentException("Duplicate JSON input property");frame.put("key",false);}
}
}
return result;
}
static String positive_id(String value){try{if(value==null||!value.matches("[1-9][0-9]*")||Long.parseLong(value)<=0)throw new IllegalArgumentException();return value;}catch(RuntimeException error){throw new IllegalArgumentException("Use a positive record ID");}}
static void print_value(Object value){try{String text=value instanceof String?(String)value:JSON.toJson(value);System.out.write((text+"\n").getBytes(StandardCharsets.UTF_8));}catch(IOException error){throw new UncheckedIOException(error);}}
static void require_condition(boolean value,String message){if(!value)throw new IllegalStateException(message);}
static String response_status(Result value){return Integer.toString(value.status);}
static Object single(Object value){List<Object> rows=items(value);if(rows.size()!=1)throw new IllegalStateException("Expected exactly one selected record");return rows.get(0);}
static void validate_crm_event_inputs(String key, String name, String start, String end) throws IOException {
crm_text(name, "EXHIBITDAY_EVENT_NAME", 500);
crm_text(key, "EXHIBITDAY_EXTERNAL_EVENT_KEY", 3000);
if (name.indexOf('<') >= 0 || name.indexOf('>') >= 0 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0 || name.equalsIgnoreCase("null"))
throw new Journal.Refusal("Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null");
crm_date(start, "EXHIBITDAY_START_DATE");
crm_date(end, "EXHIBITDAY_END_DATE");
if (end.compareTo(start) < 0) throw new Journal.Refusal("EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE");
}
static void crm_text(String value, String label, int limit) throws IOException {
Journal.strings(List.of(value));
if (value.isEmpty() || crm_space(value.charAt(0)) || crm_space(value.charAt(value.length()-1)))
throw new Journal.Refusal("Remove whitespace at the start or end of " + label);
if (value.length() > limit) throw new Journal.Refusal(label + " exceeds " + limit + " UTF-16 code units");
}
static boolean crm_space(char c) {
return Character.isWhitespace(c) && !(c >= 0x1C && c <= 0x1F) || Character.isSpaceChar(c) || c == 0x85;
}
static void crm_date(String value, String label) {
boolean valid;
try { valid = value.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}") && LocalDate.parse(value).getYear() >= 1753; }
catch (java.time.format.DateTimeParseException error) { valid = false; }
if (!valid) throw new Journal.Refusal(label + " must be a calendar date in YYYY-MM-DD on or after 1753-01-01");
}
static void run()throws Exception {
String external_event_key = required("EXHIBITDAY_EXTERNAL_EVENT_KEY");
String desired_event_name = required("EXHIBITDAY_EVENT_NAME");
String desired_start_date = required("EXHIBITDAY_START_DATE");
String desired_end_date = required("EXHIBITDAY_END_DATE");
String desired_dates_json = required("EXHIBITDAY_EXHIBIT_DATES_JSON");
String desired_section_name = optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning");
String setup_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100"));
List<Object> desired_setup_dates = items(parse_json(desired_dates_json));
validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date);
String journal_path = required("EXHIBITDAY_JOURNAL");
String stable_job_id = required("EXHIBITDAY_JOB_ID");
String job_mode = optional("EXHIBITDAY_JOB_MODE", "resume");
Result setup_workspace_response = call("workspace_binding", map(), null, null);
require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object setup_workspace = setup_workspace_response.body;
String owned_workspace_id = positive_id(text(field(setup_workspace, "id")));
String setup_input_fingerprint = journal_fingerprint(map("workflow_contract_sha256", "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key", external_event_key, "name", desired_event_name, "start_date", desired_start_date, "end_date", desired_end_date, "section_name", desired_section_name, "dates", desired_dates_json));
try (Journal setup_job = open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, Arrays.asList(Arrays.asList("create_event", "POST", "/v1/events"), Arrays.asList("update_event", "PATCH", "/v1/events"), Arrays.asList("create_section", "POST", "/v1/tasks/sections"), Arrays.asList("save_dates", "PATCH", "/v1/events/dates")), job_mode)) {
String setup_event_id = "";
String setup_section_id = "";
String recorded_section_name = desired_section_name;
if (journal_completed(setup_job, "create_event")) {
Object recorded_event = journal_recorded(setup_job, "create_event");
setup_event_id = positive_id(text(field(recorded_event, "id")));
require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.");
} else {
String event_search_offset = "0";
Map<String,Object> event_search_query = map("filter_by_integration_metadata_field_1", external_event_key, "$limit", setup_page_size);
while (true) {
event_search_query.put("$offset", event_search_offset);
Result event_search_response = call("find_existing", event_search_query, null, null);
require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object event_search_page = event_search_response.body;
List<Object> event_search_rows = items(field(event_search_page, "list_data"));
require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.");
require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.");
require_condition(either(equal(field(event_search_page, "has_more"), true), equal(field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value.");
for (Object event_search_row : items(event_search_rows)) {
if (equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key)) {
String event_search_candidate_id = positive_id(text(field(event_search_row, "id")));
if (is_present(setup_event_id)) {
require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.");
}
setup_event_id = event_search_candidate_id;
}
}
if (equal(field(event_search_page, "has_more"), false)) {
break;
}
require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.");
event_search_offset = add_offset(event_search_offset, count(event_search_rows));
}
if (not_value(is_present(setup_event_id))) {
String event_write_fingerprint = journal_fingerprint(map("name", desired_event_name, "start_date", desired_start_date, "end_date", desired_end_date, "integration_metadata_field_1", external_event_key));
Object event_intent = journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint);
Result event_create_response = call("create_event", map(), map("name", desired_event_name, "start_date", desired_start_date, "end_date", desired_end_date, "integration_metadata_field_1", external_event_key), text(field(event_intent, "idempotency_key")));
require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object created_event = event_create_response.body;
setup_event_id = positive_id(text(field(created_event, "id")));
require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.");
require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.");
journal_acknowledge(setup_job, "create_event", map("id", setup_event_id, "integration_metadata_field_1", external_event_key));
}
}
Result event_confirmation_response = call("confirm_event", map("id", setup_event_id, "$include_record_revision", "true"), null, null);
require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object confirmed_setup_event = event_confirmation_response.body;
require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.");
if (not_value(journal_completed(setup_job, "create_event"))) {
journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", map("id", text(field(confirmed_setup_event, "id")), "integration_metadata_field_1", text(field(confirmed_setup_event, "integration_metadata_field_1"))));
}
String setup_event_revision = text(field(confirmed_setup_event, "record_revision"));
require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.");
require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.");
if (journal_completed(setup_job, "update_event")) {
Object recorded_event_update = journal_recorded(setup_job, "update_event");
require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.");
require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.");
} else {
if (both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) {
journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", map("id", setup_event_id, "integration_metadata_field_1", external_event_key));
} else {
require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.");
Object event_update_body = map("id", setup_event_id, "expected_revision", setup_event_revision);
if (not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name))) {
((Map<String, Object>)event_update_body).put("name", desired_event_name);
}
if (not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date))) {
((Map<String, Object>)event_update_body).put("start_date", desired_start_date);
}
if (not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date))) {
((Map<String, Object>)event_update_body).put("end_date", desired_end_date);
}
String event_update_fingerprint = journal_fingerprint(event_update_body);
journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint);
Result event_update_response = call("update_event", map(), event_update_body, null);
require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object event_update_ack = event_update_response.body;
String event_updated_revision = text(field(event_update_ack, "record_revision"));
require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.");
journal_acknowledge(setup_job, "update_event", map("id", setup_event_id, "integration_metadata_field_1", external_event_key, "record_revision", event_updated_revision));
}
}
Result event_update_verify_response = call("verify_event_update", map("id", setup_event_id), null, null);
require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object verified_setup_event = event_update_verify_response.body;
require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.");
if (journal_completed(setup_job, "create_section")) {
Object recorded_section = journal_recorded(setup_job, "create_section");
setup_section_id = positive_id(text(field(recorded_section, "id")));
require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.");
recorded_section_name = text(field(recorded_section, "name"));
} else {
String section_search_offset = "0";
Map<String,Object> section_search_query = map("filter_by_event_id", setup_event_id, "$limit", setup_page_size);
while (true) {
section_search_query.put("$offset", section_search_offset);
Result section_search_response = call("find_section", section_search_query, null, null);
require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object section_search_page = section_search_response.body;
List<Object> section_search_rows = items(field(section_search_page, "list_data"));
require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.");
require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.");
require_condition(either(equal(field(section_search_page, "has_more"), true), equal(field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value.");
for (Object section_search_row : items(section_search_rows)) {
require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.");
if (equal(text(field(section_search_row, "name")), desired_section_name)) {
String section_search_candidate_id = positive_id(text(field(section_search_row, "id")));
if (is_present(setup_section_id)) {
require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.");
}
setup_section_id = section_search_candidate_id;
}
}
if (equal(field(section_search_page, "has_more"), false)) {
break;
}
require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.");
section_search_offset = add_offset(section_search_offset, count(section_search_rows));
}
if (not_value(is_present(setup_section_id))) {
String section_write_fingerprint = journal_fingerprint(map("event_id", setup_event_id, "name", desired_section_name));
Object section_intent = journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint);
Result section_create_response = call("create_section", map(), map("event_id", setup_event_id, "name", desired_section_name), text(field(section_intent, "idempotency_key")));
require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object created_section = section_create_response.body;
setup_section_id = positive_id(text(field(created_section, "id")));
require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.");
recorded_section_name = text(field(created_section, "name"));
require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.");
journal_acknowledge(setup_job, "create_section", map("id", setup_section_id, "event_id", setup_event_id, "name", recorded_section_name));
}
}
Result section_confirmation_response = call("confirm_section", map("id", setup_section_id), null, null);
require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object confirmed_setup_section = section_confirmation_response.body;
require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.");
if (not_value(journal_completed(setup_job, "create_section"))) {
journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", map("event_id", text(field(confirmed_setup_section, "event_id")), "id", text(field(confirmed_setup_section, "id")), "name", text(field(confirmed_setup_section, "name"))));
}
Result setup_dates_response = call("read_dates", map("event_id", setup_event_id, "filter_by_date_type_id", "1", "$include_record_revision", "true"), null, null);
require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object setup_dates_page = setup_dates_response.body;
require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.");
Object setup_dates_group = single(field(setup_dates_page, "list_data"));
require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.");
String setup_dates_revision = text(field(setup_dates_group, "record_revision"));
require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.");
if (journal_completed(setup_job, "save_dates")) {
Object recorded_dates = journal_recorded(setup_job, "save_dates");
require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.");
} else {
String setup_dates_fingerprint = journal_fingerprint(map("event_id", setup_event_id, "date_type_id", "1", "dates", desired_dates_json, "expected_revision", setup_dates_revision));
journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint);
Result setup_dates_save_response = call("save_dates", map(), map("event_id", setup_event_id, "date_type_id", "1", "dates", desired_setup_dates, "expected_revision", setup_dates_revision), null);
require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object setup_dates_ack = setup_dates_save_response.body;
String setup_dates_saved_revision = text(field(setup_dates_ack, "record_revision"));
require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.");
journal_acknowledge(setup_job, "save_dates", map("event_id", setup_event_id, "date_type_id", "1", "record_revision", setup_dates_saved_revision));
}
Result setup_dates_verify_response = call("verify_dates", map("event_id", setup_event_id, "filter_by_date_type_id", "1"), null, null);
require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object setup_dates_verify_page = setup_dates_verify_response.body;
require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.");
Object setup_dates_verify_group = single(field(setup_dates_verify_page, "list_data"));
require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.");
require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.");
Result setup_event_readback_response = call("event_readback", map("id", setup_event_id), null, null);
require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.");
Object setup_event_readback = setup_event_readback_response.body;
require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.");
require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.");
boolean planning_section_present = false;
for (Object setup_event_section : items(items(field(setup_event_readback, "task_sections")))) {
if (equal(text(field(setup_event_section, "id")), setup_section_id)) {
planning_section_present = true;
}
}
require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.");
print_value(map("event_id", setup_event_id, "task_section_id", setup_section_id, "dates_verified", "true"));
}
}
public static void main(String[] args)throws Exception {run();}
}
<?php
// PHP 8.1+ with the cURL extension. Set EXHIBITDAY_API_KEY before running.
declare(strict_types=1);
const BASE = 'https://api.exhibitday.com/v1';
const SPEC = '{"preserveNumbers":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"find_existing":{"method":"GET","path":"/events"},"create_event":{"method":"POST","path":"/events"},"confirm_event":{"method":"GET","path":"/events/info"},"update_event":{"method":"PATCH","path":"/events"},"verify_event_update":{"method":"GET","path":"/events/info"},"find_section":{"method":"GET","path":"/tasks/sections"},"create_section":{"method":"POST","path":"/tasks/sections"},"confirm_section":{"method":"GET","path":"/tasks/sections/info"},"read_dates":{"method":"GET","path":"/events/dates"},"save_dates":{"method":"PATCH","path":"/events/dates"},"verify_dates":{"method":"GET","path":"/events/dates"},"event_readback":{"method":"GET","path":"/events/info"}}}';
$spec = json_decode(SPEC, true, 512, JSON_THROW_ON_ERROR);
$apiKey = required('EXHIBITDAY_API_KEY');
if(preg_match('/[^\x20-\x7e]/',$apiKey))throw new RuntimeException('Use the API key as one ASCII header value without control characters');
if (trim($apiKey) === '') throw new RuntimeException('Set EXHIBITDAY_API_KEY');
function required(string $name, bool $allowEmpty = false): string {
$value = getenv($name);
if ($value === false || (!$allowEmpty && $value === '')) {
throw new RuntimeException('Set ' . $name);
}
return $value;
}
function optional(string $name, string $fallback): string {
$value = getenv($name);
return $value === false ? $fallback : $value;
}
function decodeJson(string $text): mixed {
global $spec;
if ($spec['preserveNumbers']) {
// Quote NUMBER tokens without changing digits inside JSON strings; CSV decimals stay exact.
$pattern = <<<'JSON_NUMBER'
~"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?~
JSON_NUMBER;
$text = preg_replace_callback($pattern, static function (array $match): string {
return str_starts_with($match[0], '"') ? $match[0] : json_encode($match[0], JSON_THROW_ON_ERROR);
}, $text);
if ($text === null) throw new RuntimeException('Unable to preserve decimal tokens');
}
return json_decode($text, true, 512, JSON_THROW_ON_ERROR);
}
function nativeTransport(string $method, string $url, array $headers, ?string $data): array {
$responseHeaders = [];
$handle = curl_init($url);
if ($handle === false) throw new RuntimeException('Unable to initialize cURL');
$headerLines = [];
foreach ($headers as $name => $value) $headerLines[] = $name . ': ' . $value;
$options = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => $headerLines,
CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$responseHeaders): int {
if (str_starts_with($line, 'HTTP/')) $responseHeaders = [];
$separator = strpos($line, ':');
if ($separator !== false) {
$responseHeaders[strtolower(trim(substr($line, 0, $separator)))] = trim(substr($line, $separator + 1));
}
return strlen($line);
}];
if ($data !== null) $options[CURLOPT_POSTFIELDS] = $data;
try {
curl_setopt_array($handle, $options);
$raw = curl_exec($handle);
if ($raw === false) throw new RuntimeException('Network request failed: ' . curl_error($handle));
return [(int)curl_getinfo($handle, CURLINFO_RESPONSE_CODE), $raw, $responseHeaders];
} finally {
curl_close($handle);
}
}
function retryDelay(array $headers, int $attempt): float {
$value = $headers['retry-after'] ?? '';
if (is_numeric($value)) return max(0.0, (float)$value);
$date = $value === '' ? false : strtotime($value);
return $date === false ? (float)(2 ** $attempt) : max(0.0, (float)($date - time()));
}
// An API error response. Branch on errorCode (and status), never on the message text.
// $uncertain is true when a PATCH or DELETE got no response or a server error: it may or may not have been applied.
final class ApiException extends RuntimeException {
public function __construct(public readonly int $status, public readonly ?string $errorCode, string $message, public readonly bool $uncertain = false) {
parent::__construct($message);
}
}
function call(string $name, array $params = [], mixed $body = null, ?string $key = null): array {
global $spec, $apiKey, $transport;
$route = $spec['requests'][$name];
$headers = ['Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json'];
if ($route['method'] === 'POST') {
if ($key === null || $key === '') throw new RuntimeException('Persist a logical create key before sending POST');
$headers['Idempotency-Key'] = $key; // ONCE, before retries.
}
$data = $body === null ? null : json_encode($body, JSON_THROW_ON_ERROR);
if ($data !== null) $headers['Content-Type'] = 'application/json';
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$url = BASE . $route['path'] . ($query === '' ? '' : '?' . $query);
// Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
// server error is never resent blindly: it may already have been applied, so the caller reads the record first.
$resend = $route['method'] === 'GET';
for ($attempt = 0; $attempt < 5; $attempt++) {
try {
[$status, $raw, $responseHeaders] = $transport($route['method'], $url, $headers, $data);
} catch (RuntimeException $error) {
if (!$resend) throw new ApiException(0, null, 'No response', true);
if ($attempt === 4) throw $error;
usleep((int)((2 ** $attempt) * 1000000));
continue;
}
$responseHeaders = array_change_key_case($responseHeaders, CASE_LOWER);
$result = null;
if ($status !== 304 && $raw !== '') {
try { $result = decodeJson($raw); }
catch (JsonException $error) {
if ($status < 400) throw new RuntimeException('Expected a JSON success response', 0, $error);
}
}
if ($status >= 500 && !$resend) {
throw new ApiException($status, is_array($result) && isset($result['error_code']) ? (string)$result['error_code'] : null, 'HTTP ' . $status, true);
}
$retry = $resend && ($status === 429 || $status >= 500);
if ($retry) {
if ($attempt === 4) throw new RuntimeException('Retry limit reached; check the outcome before starting a new create');
usleep((int)(retryDelay($responseHeaders, $attempt) * 1000000));
continue;
}
if ($status >= 400) {
if (!is_array($result)) throw new ApiException($status, null, 'HTTP ' . $status);
throw new ApiException($status, isset($result['error_code']) ? (string)$result['error_code'] : null, json_encode(['error_code' => $result['error_code'] ?? null,
'error_params' => $result['error_params'] ?? null, 'errors' => $result['errors'] ?? null,
'request_id' => $result['request_id'] ?? null], JSON_THROW_ON_ERROR));
}
return ['status' => $status, 'body' => $result, 'headers' => $responseHeaders, 'raw' => $raw];
}
throw new RuntimeException('Retry limit reached');
}
$transport = Closure::fromCallable('nativeTransport');
function add_offset(string $offset,int $received):string{$result=(int)$offset+$received;if($received<=0||$result>2147483647)throw new RuntimeException("Cannot advance this int32 offset; reconcile the query");return (string)$result;}
function both(bool $left,bool $right):bool{return $left&&$right;}
function deep_equal(mixed $left,mixed $right):bool {
if(is_object($left))$left=get_object_vars($left);if(is_object($right))$right=get_object_vars($right);
if(gettype($left)!==gettype($right))return false;
if(!is_array($left))return$left===$right;
if(array_is_list($left)!==array_is_list($right)||count($left)!==count($right))return false;
foreach($left as$key=>$value)if(!array_key_exists($key,$right)||!deep_equal($value,$right[$key]))return false;
return true;
}
function either(bool $left,bool $right):bool{return $left||$right;}
function equal(mixed $left,mixed $right):bool{return $left===$right;}
function field(mixed $value,string $name):mixed{if(!is_array($value)||!array_key_exists($name,$value))throw new RuntimeException("Missing response field: ".$name);return $value[$name];}
function items(mixed $value):array{if(!is_array($value)||!array_is_list($value))throw new RuntimeException("Expected a JSON array");return $value;}
function is_empty(mixed $value):bool{return count(items($value))===0;}
function is_present(?string $value):bool{return $value!==null&&$value!=="";}
final class JournalRefusal extends RuntimeException {}
final class JournalProtocol
{
public const PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n";
public static function utf8(mixed $value):string
{if(!is_string($value)||preg_match('//u',$value)!==1)throw new JournalRefusal('Journal fields must be exact valid UTF8 strings');return$value;}
public static function strings(array $values):string
{$raw='';foreach($values as$value){$item=self::utf8($value);$raw.=strlen($item).':'.$item;}return$raw;}
private static function length(string $text,int $remaining):int
{if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$text))throw new JournalRefusal('Noncanonical string length');$maximum=(string)$remaining;if(strlen($text)>strlen($maximum)||(strlen($text)===strlen($maximum)&&strcmp($text,$maximum)>0))throw new JournalRefusal('Incomplete journal string/frame');return(int)$text;}
public static function readStrings(string $raw):array
{$values=[];$offset=0;while($offset<strlen($raw)){$end=strpos($raw,':',$offset);if($end===false)throw new JournalRefusal('Incomplete string length');$text=substr($raw,$offset,$end-$offset);$offset=$end+1;$size=self::length($text,strlen($raw)-$offset);$values[]=self::utf8(substr($raw,$offset,$size));$offset+=$size;}return$values;}
public static function digest(string $raw):string{return strtoupper(hash('sha256',$raw));}
public static function fingerprint(array $pairs):string
{$names=array_keys($pairs);sort($names,SORT_STRING);$values=[];foreach($names as$name){if(!is_string($name)||!preg_match('/\A[A-Za-z0-9_.-]+\z/',$name)||in_array(strtolower($name),['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use explicit secret-free fingerprint names');$values[]=$name;$values[]=$pairs[$name];}return self::digest(self::strings($values));}
public static function frame(array $values):string
{$payload=self::strings($values);return strlen($payload).' '.self::digest($payload)."\n".$payload."\n";}
public static function decode(string $raw):array
{if(!str_starts_with($raw,self::PREAMBLE))throw new JournalRefusal('Unknown or incomplete journal version');$offset=strlen(self::PREAMBLE);$records=[];
while($offset<strlen($raw)){$end=strpos($raw,"\n",$offset);if($end===false)throw new JournalRefusal('Incomplete frame header; reconcile before retry');$header=substr($raw,$offset,$end-$offset);if(!preg_match('/\A(0|[1-9][0-9]*) ([0-9A-F]{64})\z/',$header,$match))throw new JournalRefusal('Invalid frame header');$offset=$end+1;$size=self::length($match[1],strlen($raw)-$offset);if($size>=strlen($raw)-$offset)throw new JournalRefusal('Incomplete frame; reconcile before retry');$payload=substr($raw,$offset,$size);$offset+=$size;if($raw[$offset]!=="\n"||self::digest($payload)!==$match[2])throw new JournalRefusal('Journal integrity failed; reconcile before retry');$records[]=self::readStrings($payload);$offset++;}return$records;}
public static function writeAll($file,string $raw):void
{$offset=0;while($offset<strlen($raw)){$count=fwrite($file,substr($raw,$offset));if($count===false||$count===0)throw new RuntimeException('Journal write did not advance');$offset+=$count;}if(!fflush($file)||!fsync($file))throw new RuntimeException('Journal flush failed; stop and reconcile');}
public static function createPrivate(string $path)
{$mask=umask(0077);try{$file=@fopen($path,'x+b');}finally{umask($mask);}if($file===false)throw new JournalRefusal('Cannot create private journal/lock; check path and do not steal an existing lock');return$file;}
}
final class GuideJournal
{
private string $path,$lockPath,$owner;private array $header,$allowed=[],$intents=[],$savedValues=[],$adoptedValues=[],$identity=[];
private $file=null;private bool $owned=false,$tainted=false;
public function __construct(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode='resume')
{
if(!function_exists('fsync'))throw new JournalRefusal('This runtime must provide native fsync; no permissive fallback');
$this->path=$path;$this->lockPath=$path.'.lock';$this->owner=bin2hex(random_bytes(16));$address=parse_url($base);
if($address===false||!in_array($address['scheme']??null,['https','http'],true)||!isset($address['host'])||isset($address['user'])||isset($address['pass'])||isset($address['query'])||isset($address['fragment'])||!preg_match('/\A[a-z][a-z0-9-]*\z/',$slug))throw new JournalRefusal('Use actual API base and closed guide slug');
if(trim($job)===''||!preg_match('/\A[1-9][0-9]*\z/',$workspace)||!preg_match('/\A[0-9A-F]{64}\z/',$inputFingerprint))throw new JournalRefusal('Use actual workspace, stable explicit job ID and exact fingerprint');
if(!in_array($mode,['new','resume'],true))throw new JournalRefusal('Choose new or resume for this local job');
$manifest=[];foreach($writes as$write){if(!is_array($write)||!array_is_list($write)||count($write)!==3)throw new JournalRefusal('Invalid write manifest');[$step,$method,$route]=$write;
if(!is_string($step)||!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->allowed[$step])||!in_array($method,['POST','PATCH','DELETE'],true)||!is_string($route)||!preg_match('~\A/v1/[A-Za-z0-9_/-]+\z~',$route)||str_contains($route,'//'))throw new JournalRefusal('Use a closed unique write manifest');$this->allowed[$step]=[$method,$route];array_push($manifest,$step,$method,$route);}
if($this->allowed===[])throw new JournalRefusal('Only write workflows need restart journal');$this->header=['H','1',$base,$workspace,$slug,$job,$inputFingerprint,JournalProtocol::digest(JournalProtocol::strings($manifest))];JournalProtocol::strings($this->header);
$this->file=JournalProtocol::createPrivate($this->lockPath);$this->owned=true;
try{
JournalProtocol::writeAll($this->file,$this->owner);$identity=fstat($this->file);if($identity===false)throw new JournalRefusal('Cannot bind acquired lock identity');$this->identity=$identity;
clearstatcache(true,$path);if(is_link($path))throw new JournalRefusal('Choose private regular journal file');
$exists=file_exists($path);if($mode==='resume'&&!$exists)throw new JournalRefusal('Journal missing: stop and reconcile lost state before starting a new logical job');if($mode==='new'&&$exists)throw new JournalRefusal('Journal exists; use resume for the same logical job');
if($mode==='new'){$target=JournalProtocol::createPrivate($path);try{JournalProtocol::writeAll($target,JournalProtocol::PREAMBLE.JournalProtocol::frame($this->header));}finally{fclose($target);}}
$raw=file_get_contents($path);if($raw===false)throw new JournalRefusal('Cannot read journal');$records=JournalProtocol::decode($raw);if($records===[]||$records[0]!==$this->header)throw new JournalRefusal('Journal workspace/base/guide/job/input binding differs');foreach(array_slice($records,1)as$record)$this->apply($record);
if(array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Saved intent lacks ACK; stop and reconcile before retry');
}catch(Throwable $error){$this->close();throw$error;}
}
private function apply(array $record):void
{
if(($record[0]??null)==='I'){
if(count($record)!==6)throw new JournalRefusal('Invalid intent shape');[,$step,$method,$route,$fingerprint,$key]=$record;
if(!preg_match('/\A[a-z][a-z0-9_-]*\z/',$step)||isset($this->intents[$step])||isset($this->adoptedValues[$step])||($this->allowed[$step]??null)!==[$method,$route]||!preg_match('/\A[0-9A-F]{64}\z/',$fingerprint)||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Invalid, future or repeated intent');
if(($method==='POST'&&!preg_match('/\A[0-9a-f]{32}\z/',$key))||($method!=='POST'&&$key!==''))throw new JournalRefusal('Invalid persisted action key');$this->intents[$step]=['method'=>$method,'path'=>$route,'request_fingerprint'=>$fingerprint,'idempotency_key'=>$key];
}elseif(($record[0]??null)==='A'){
if(count($record)<3)throw new JournalRefusal('Invalid ACK shape');[,$step,$count]=$record;$pairs=array_slice($record,3);
if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0||!isset($this->intents[$step])||isset($this->savedValues[$step]))throw new JournalRefusal('ACK without exactly one prior intent');
$names=[];for($i=0;$i<count($pairs);$i+=2)$names[]=$pairs[$i];$unique=array_values(array_unique($names,SORT_STRING));sort($unique,SORT_STRING);
if($names!==$unique)throw new JournalRefusal('ACK fields must be unique sorted names');$saved=[];foreach($names as$i=>$name){if(!preg_match('/\A[a-z][a-z0-9_]*\z/',$name)||in_array($name,['api_key','exhibitday_api_key'],true))throw new JournalRefusal('Use secret-free ACK field names');$saved[$name]=$pairs[$i*2+1];}$this->savedValues[$step]=$saved;
}elseif(($record[0]??null)==='S'){
if(count($record)<6)throw new JournalRefusal('Invalid read-adoption shape');[,$step,$method,$route,$readFingerprint,$count]=$record;$pairs=array_slice($record,6);
$completed=array_unique(array_merge(array_keys($this->savedValues),array_keys($this->adoptedValues)),SORT_STRING);$order=array_keys($this->allowed);$prefix=array_slice($order,0,count($completed));$sorted=$completed;sort($sorted,SORT_STRING);sort($prefix,SORT_STRING);
if(count($completed)>=count($order)||$sorted!==$prefix||$step!==$order[count($completed)]||array_diff(array_keys($this->intents),array_keys($this->savedValues))!==[])throw new JournalRefusal('Adopt only the exact next setup action without any pending intent');
$target=$this->allowed[$step];$expected=($target===['POST','/v1/events']||$step==='update_event'&&$target===['PATCH','/v1/events'])?'/v1/events/info':($target===['POST','/v1/tasks/sections']?'/v1/tasks/sections/info':null);
if($method!=='GET'||$expected===null||$route!==$expected)throw new JournalRefusal('Adoption requires the exact source-bound single Event or section read');
if(!preg_match('/\A(?:0|[1-9][0-9]*)\z/',$count)||(string)intdiv(count($pairs),2)!==$count||count($pairs)%2!==0)throw new JournalRefusal('Invalid read-adoption field count');
$names=[];for($i=0;$i<count($pairs);$i+=2)$names[]=$pairs[$i];$fields=$expected==='/v1/events/info'?['id','integration_metadata_field_1']:['event_id','id','name'];
if($names!==$fields)throw new JournalRefusal('Read-adoption fields must match the exact source tuple');$saved=[];foreach($names as$i=>$name)$saved[$name]=$pairs[$i*2+1];
foreach(['id','event_id']as$name)if(isset($saved[$name])&&(!preg_match('/\A[1-9][0-9]*\z/',$saved[$name])||strlen($saved[$name])>19||(strlen($saved[$name])===19&&strcmp($saved[$name],'9223372036854775807')>0)))throw new JournalRefusal('Read-adoption IDs must be exact positive Int64 strings');
foreach($fields as$name)if(!in_array($name,['id','event_id'],true)&&$saved[$name]==='')throw new JournalRefusal('Read-adoption material must be complete and fingerprint-bound');
if($readFingerprint!==JournalProtocol::fingerprint($saved))throw new JournalRefusal('Read-adoption material must be complete and fingerprint-bound');$this->adoptedValues[$step]=$saved;
}else throw new JournalRefusal('Unknown journal transition');
}
private function requireActive():void
{
if(!$this->owned||$this->file===null||$this->tainted)throw new JournalRefusal('Journal closed or IO outcome needs reconciliation');clearstatcache(true,$this->lockPath);$current=@lstat($this->lockPath);$token=@file_get_contents($this->lockPath);
if($current===false||($current['dev']??null)!==($this->identity['dev']??null)||($current['ino']??null)!==($this->identity['ino']??null)||$token!==$this->owner)throw new JournalRefusal('Journal lock replaced; stop without deleting it');
}
private function append(array $record):void
{
$this->requireActive();$raw=JournalProtocol::frame($record);$target=null;
try{$target=@fopen($this->path,'ab');if($target===false)throw new JournalRefusal('Cannot append journal; stop and reconcile');JournalProtocol::writeAll($target,$raw);}catch(Throwable $error){$this->tainted=true;throw$error;}finally{if(is_resource($target))fclose($target);}
}
public function acknowledged(string $step):bool{$this->requireActive();return isset($this->savedValues[$step]);}
public function saved(string $step):array{$this->requireActive();if(!isset($this->savedValues[$step]))throw new JournalRefusal('No acknowledged state exists');return$this->savedValues[$step];}
public function completed(string $step):bool{$this->requireActive();return isset($this->savedValues[$step])||isset($this->adoptedValues[$step]);}
public function adopted(string $step):bool{$this->requireActive();return isset($this->adoptedValues[$step]);}
public function recorded(string $step):array{$this->requireActive();if(!$this->completed($step))throw new JournalRefusal('No completed write or read-adoption exists');return$this->savedValues[$step]??$this->adoptedValues[$step];}
public function adopt(string $step,string $method,string $route,array $saved):void{$this->requireActive();$record=['S',$step,$method,$route,JournalProtocol::fingerprint($saved),(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->adoptedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->adoptedValues=$previous;}$this->append($record);$this->apply($record);}
public function beginAction(string $step,string $method,string $route,string $requestFingerprint):array
{
$this->requireActive();if(isset($this->intents[$step]))throw new JournalRefusal('Never blindly repeat an existing action');$key=$method==='POST'?bin2hex(random_bytes(16)):'';$record=['I',$step,$method,$route,$requestFingerprint,$key];$previous=$this->intents;try{$this->apply($record);}finally{$this->intents=$previous;}$this->append($record);$this->apply($record);return$this->intents[$step];
}
public function acknowledge(string $step,array $saved):void
{
$this->requireActive();$record=['A',$step,(string)count($saved)];$names=array_keys($saved);sort($names,SORT_STRING);foreach($names as$name){$record[]=$name;$record[]=$saved[$name];}$previous=$this->savedValues;try{$this->apply($record);JournalProtocol::strings($record);}finally{$this->savedValues=$previous;}$this->append($record);$this->apply($record);
}
public function close():void
{
if(!$this->owned)return;if($this->tainted){fclose($this->file);$this->file=null;$this->owned=false;return;}
try{$this->requireActive();}catch(Throwable $error){fclose($this->file);$this->file=null;$this->owned=false;throw$error;}fclose($this->file);$this->file=null;$this->owned=false;if(!unlink($this->lockPath))throw new JournalRefusal('Could not release owned journal lock');
}
}
function journal_values(mixed $value):array{if(!is_object($value))throw new JournalRefusal('Saved/fingerprint values need an explicit object');$result=get_object_vars($value);foreach($result as$name=>$item)if(!is_string($name)||!is_string($item))throw new JournalRefusal('Saved/fingerprint values must be exact strings');return$result;}
function journal_acknowledge(GuideJournal $job,string $step,mixed $saved):void{$job->acknowledge($step,journal_values($saved));}
function journal_acknowledged(GuideJournal $job,string $step):bool{return $job->acknowledged($step);}
function journal_adopt(GuideJournal $job,string $step,string $method,string $path,mixed $saved):void{$job->adopt($step,$method,$path,journal_values($saved));}
function journal_begin(GuideJournal $job,string $step,string $method,string $path,string $requestFingerprint):array{return $job->beginAction($step,$method,$path,$requestFingerprint);}
function journal_completed(GuideJournal $job,string $step):bool{return$job->completed($step);}
function journal_fingerprint(mixed $value):string{return JournalProtocol::fingerprint(journal_values($value));}
function journal_recorded(GuideJournal $job,string $step):array{return$job->recorded($step);}
function not_value(bool $value):bool{return !$value;}
function open_journal(string $path,string $base,string $workspace,string $slug,string $job,string $inputFingerprint,array $writes,string $mode):GuideJournal{return new GuideJournal($path,$base,$workspace,$slug,$job,$inputFingerprint,$writes,$mode);}
function page_size(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>10||(strlen($value)===10&&strcmp($value,"2147483647")>0))throw new RuntimeException("Page size must be a positive int32");return $value;}
function parse_json(string $value):mixed{
$result=json_decode($value,false,512,JSON_THROW_ON_ERROR);$stack=[];
if(preg_match_all('~"(?:\\\\.|[^"\\\\])*"|[{}\[\],]~s',$value,$matches)===false)throw new RuntimeException('JSON token validation failed');
foreach($matches[0]as$token){
if($token==='{')$stack[]=['object'=>true,'key'=>true,'names'=>[]];
elseif($token==='[')$stack[]=['object'=>false];
elseif($token==='}'||$token===']')array_pop($stack);
elseif($token===','){if($stack!==[]&&$stack[count($stack)-1]['object'])$stack[count($stack)-1]['key']=true;}
elseif($stack!==[]&&$stack[count($stack)-1]['object']&&$stack[count($stack)-1]['key']){$at=count($stack)-1;$name=json_decode($token,false,512,JSON_THROW_ON_ERROR);if(array_key_exists($name,$stack[$at]['names']))throw new RuntimeException('Duplicate JSON input property');$stack[$at]['names'][$name]=true;$stack[$at]['key']=false;}
}
$finite=function(mixed $node)use(&$finite):void{if(is_float($node)&&!is_finite($node))throw new RuntimeException('Use finite JSON numbers');if(is_object($node)||is_array($node))foreach($node as$item)$finite($item);};$finite($result);return$result;
}
function positive_id(string $value):string{if(!preg_match("/^[1-9][0-9]*$/D",$value)||strlen($value)>19||(strlen($value)===19&&strcmp($value,"9223372036854775807")>0))throw new RuntimeException("Use a positive record ID");return $value;}
function print_value(mixed $value):void{echo (is_string($value)?$value:json_encode($value,JSON_THROW_ON_ERROR))."\n";}
function require_condition(bool $value,string $message):void{if(!$value)throw new RuntimeException($message);}
function response_status(array $value):string{return(string)$value["status"];}
function single(mixed $value):mixed{$rows=items($value);if(count($rows)!==1)throw new RuntimeException('Expected exactly one selected record');return$rows[0];}
function text(mixed $value):string{if($value===null)return "";if(is_string($value))return $value;if(is_bool($value))return $value?"true":"false";if(is_int($value))return (string)$value;throw new RuntimeException("Expected a scalar response value");}
function validate_crm_event_inputs(string $key, string $name, string $start, string $end): void {
$spaces = '[\x{0009}-\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]';
foreach ([[$name,'EXHIBITDAY_EVENT_NAME',500],[$key,'EXHIBITDAY_EXTERNAL_EVENT_KEY',3000]] as [$value,$label,$limit]) {
JournalProtocol::utf8($value);
if ($value === '' || preg_match('~\A'.$spaces.'|'.$spaces.'\z~u', $value))
throw new JournalRefusal('Remove whitespace at the start or end of '.$label);
if (preg_match_all('/./us',$value) + preg_match_all('/[\x{10000}-\x{10FFFF}]/u',$value) > $limit)
throw new JournalRefusal($label.' exceeds '.$limit.' UTF-16 code units');
}
if (strpbrk($name, "<>\r\n") !== false || strtolower($name) === 'null')
throw new JournalRefusal('Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null');
foreach ([[$start,'EXHIBITDAY_START_DATE'],[$end,'EXHIBITDAY_END_DATE']] as [$value,$label]) {
if (!preg_match('/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/', $value, $match)
|| (int)$match[1] < 1753 || !checkdate((int)$match[2],(int)$match[3],(int)$match[1]))
throw new JournalRefusal($label.' must be a calendar date in YYYY-MM-DD on or after 1753-01-01');
}
if (strcmp($end,$start) < 0) throw new JournalRefusal('EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE');
}
function main():void {
$external_event_key = required('EXHIBITDAY_EXTERNAL_EVENT_KEY');
$desired_event_name = required('EXHIBITDAY_EVENT_NAME');
$desired_start_date = required('EXHIBITDAY_START_DATE');
$desired_end_date = required('EXHIBITDAY_END_DATE');
$desired_dates_json = required('EXHIBITDAY_EXHIBIT_DATES_JSON');
$desired_section_name = optional('EXHIBITDAY_TASK_SECTION_NAME', 'Pre-event planning');
$setup_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100'));
$desired_setup_dates = items(parse_json($desired_dates_json));
validate_crm_event_inputs($external_event_key, $desired_event_name, $desired_start_date, $desired_end_date);
$journal_path = required('EXHIBITDAY_JOURNAL');
$stable_job_id = required('EXHIBITDAY_JOB_ID');
$job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume');
$setup_workspace_response = call('workspace_binding', [], null, null);
require_condition(equal(response_status($setup_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$setup_workspace = $setup_workspace_response["body"];
$owned_workspace_id = positive_id(text(field($setup_workspace, 'id')));
$setup_input_fingerprint = journal_fingerprint((object)['workflow_contract_sha256' => '19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32', 'external_event_key' => $external_event_key, 'name' => $desired_event_name, 'start_date' => $desired_start_date, 'end_date' => $desired_end_date, 'section_name' => $desired_section_name, 'dates' => $desired_dates_json]);
$setup_job = open_journal($journal_path, 'https://api.exhibitday.com/v1', $owned_workspace_id, 'event-setup-crm', $stable_job_id, $setup_input_fingerprint, [['create_event', 'POST', '/v1/events'], ['update_event', 'PATCH', '/v1/events'], ['create_section', 'POST', '/v1/tasks/sections'], ['save_dates', 'PATCH', '/v1/events/dates']], $job_mode);
try {
$setup_event_id = '';
$setup_section_id = '';
$recorded_section_name = $desired_section_name;
if (journal_completed($setup_job, 'create_event')) {
$recorded_event = journal_recorded($setup_job, 'create_event');
$setup_event_id = positive_id(text(field($recorded_event, 'id')));
require_condition(equal(text(field($recorded_event, 'integration_metadata_field_1')), $external_event_key), 'The journal\'s completed Event differs from this external key.');
} else {
$event_search_offset = '0';
$event_search_query = ['filter_by_integration_metadata_field_1' => $external_event_key, '$limit' => $setup_page_size];
while (true) {
$event_search_query['$offset'] = $event_search_offset;
$event_search_response = call('find_existing', $event_search_query, null, null);
require_condition(equal(response_status($event_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$event_search_page = $event_search_response["body"];
$event_search_rows = items(field($event_search_page, 'list_data'));
require_condition(equal(text(field($event_search_page, 'records_found')), text(count($event_search_rows))), 'records_found differs from this complete page\'s rows.');
require_condition(is_present(text(field($event_search_page, 'total_records'))), 'The search wrapper needs total_records.');
require_condition(either(equal(field($event_search_page, 'has_more'), true), equal(field($event_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.');
foreach (items($event_search_rows) as $event_search_row) {
if (equal(text(field($event_search_row, 'integration_metadata_field_1')), $external_event_key)) {
$event_search_candidate_id = positive_id(text(field($event_search_row, 'id')));
if (is_present($setup_event_id)) {
require_condition(equal($setup_event_id, $event_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.');
}
$setup_event_id = $event_search_candidate_id;
}
}
if (equal(field($event_search_page, 'has_more'), false)) {
break;
}
require_condition(not_value(is_empty($event_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.');
$event_search_offset = add_offset($event_search_offset, count($event_search_rows));
}
if (not_value(is_present($setup_event_id))) {
$event_write_fingerprint = journal_fingerprint((object)['name' => $desired_event_name, 'start_date' => $desired_start_date, 'end_date' => $desired_end_date, 'integration_metadata_field_1' => $external_event_key]);
$event_intent = journal_begin($setup_job, 'create_event', 'POST', '/v1/events', $event_write_fingerprint);
$event_create_response = call('create_event', [], (object)['name' => $desired_event_name, 'start_date' => $desired_start_date, 'end_date' => $desired_end_date, 'integration_metadata_field_1' => $external_event_key], text(field($event_intent, 'idempotency_key')));
require_condition(equal(response_status($event_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$created_event = $event_create_response["body"];
$setup_event_id = positive_id(text(field($created_event, 'id')));
require_condition(equal(text(field($created_event, 'integration_metadata_field_1')), $external_event_key), 'The created Event\'s external key differs; preserve the pending intent and reconcile.');
require_condition(both(is_present(text(field($created_event, 'name'))), both(is_present(text(field($created_event, 'start_date'))), is_present(text(field($created_event, 'end_date'))))), 'The Event acknowledgement omitted its saved name or main dates.');
journal_acknowledge($setup_job, 'create_event', (object)['id' => $setup_event_id, 'integration_metadata_field_1' => $external_event_key]);
}
}
$event_confirmation_response = call('confirm_event', ['id' => $setup_event_id, '$include_record_revision' => 'true'], null, null);
require_condition(equal(response_status($event_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$confirmed_setup_event = $event_confirmation_response["body"];
require_condition(both(equal(text(field($confirmed_setup_event, 'id')), $setup_event_id), equal(text(field($confirmed_setup_event, 'integration_metadata_field_1')), $external_event_key)), 'The captured Event is missing or rebound; stop instead of searching for or creating a replacement.');
if (not_value(journal_completed($setup_job, 'create_event'))) {
journal_adopt($setup_job, 'create_event', 'GET', '/v1/events/info', (object)['id' => text(field($confirmed_setup_event, 'id')), 'integration_metadata_field_1' => text(field($confirmed_setup_event, 'integration_metadata_field_1'))]);
}
$setup_event_revision = text(field($confirmed_setup_event, 'record_revision'));
require_condition(is_present($setup_event_revision), 'Read the selected Event with its revision before comparing or updating it.');
require_condition(both(both(is_present(text(field($confirmed_setup_event, 'name'))), is_present(text(field($confirmed_setup_event, 'start_date')))), is_present(text(field($confirmed_setup_event, 'end_date')))), 'The selected Event must return its current name, start date and end date.');
if (journal_completed($setup_job, 'update_event')) {
$recorded_event_update = journal_recorded($setup_job, 'update_event');
require_condition(both(equal(text(field($recorded_event_update, 'id')), $setup_event_id), equal(text(field($recorded_event_update, 'integration_metadata_field_1')), $external_event_key)), 'The recorded Event update has a different identity. Stop and reconcile.');
require_condition(both(both(equal(text(field($confirmed_setup_event, 'name')), $desired_event_name), equal(text(field($confirmed_setup_event, 'start_date')), $desired_start_date)), equal(text(field($confirmed_setup_event, 'end_date')), $desired_end_date)), 'The Event name or main dates changed after this job checked them. Review the current Event before writing again.');
} else {
if (both(both(equal(text(field($confirmed_setup_event, 'name')), $desired_event_name), equal(text(field($confirmed_setup_event, 'start_date')), $desired_start_date)), equal(text(field($confirmed_setup_event, 'end_date')), $desired_end_date))) {
journal_adopt($setup_job, 'update_event', 'GET', '/v1/events/info', (object)['id' => $setup_event_id, 'integration_metadata_field_1' => $external_event_key]);
} else {
require_condition(not_value(journal_acknowledged($setup_job, 'create_event')), 'The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.');
$event_update_body = (object)['id' => $setup_event_id, 'expected_revision' => $setup_event_revision];
if (not_value(equal(text(field($confirmed_setup_event, 'name')), $desired_event_name))) {
$event_update_body->{'name'} = $desired_event_name;
}
if (not_value(equal(text(field($confirmed_setup_event, 'start_date')), $desired_start_date))) {
$event_update_body->{'start_date'} = $desired_start_date;
}
if (not_value(equal(text(field($confirmed_setup_event, 'end_date')), $desired_end_date))) {
$event_update_body->{'end_date'} = $desired_end_date;
}
$event_update_fingerprint = journal_fingerprint($event_update_body);
journal_begin($setup_job, 'update_event', 'PATCH', '/v1/events', $event_update_fingerprint);
$event_update_response = call('update_event', [], $event_update_body, null);
require_condition(equal(response_status($event_update_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$event_update_ack = $event_update_response["body"];
$event_updated_revision = text(field($event_update_ack, 'record_revision'));
require_condition(is_present($event_updated_revision), 'The conditional Event update needs its returned revision. Reconcile the pending request before continuing.');
journal_acknowledge($setup_job, 'update_event', (object)['id' => $setup_event_id, 'integration_metadata_field_1' => $external_event_key, 'record_revision' => $event_updated_revision]);
}
}
$event_update_verify_response = call('verify_event_update', ['id' => $setup_event_id], null, null);
require_condition(equal(response_status($event_update_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$verified_setup_event = $event_update_verify_response["body"];
require_condition(both(both(equal(text(field($verified_setup_event, 'id')), $setup_event_id), equal(text(field($verified_setup_event, 'integration_metadata_field_1')), $external_event_key)), both(both(equal(text(field($verified_setup_event, 'name')), $desired_event_name), equal(text(field($verified_setup_event, 'start_date')), $desired_start_date)), equal(text(field($verified_setup_event, 'end_date')), $desired_end_date))), 'The Event\'s current identity, name or main dates differ. Inspect the Event before continuing with setup.');
if (journal_completed($setup_job, 'create_section')) {
$recorded_section = journal_recorded($setup_job, 'create_section');
$setup_section_id = positive_id(text(field($recorded_section, 'id')));
require_condition(equal(text(field($recorded_section, 'event_id')), $setup_event_id), 'The recorded Task Section belongs to a different Event.');
$recorded_section_name = text(field($recorded_section, 'name'));
} else {
$section_search_offset = '0';
$section_search_query = ['filter_by_event_id' => $setup_event_id, '$limit' => $setup_page_size];
while (true) {
$section_search_query['$offset'] = $section_search_offset;
$section_search_response = call('find_section', $section_search_query, null, null);
require_condition(equal(response_status($section_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$section_search_page = $section_search_response["body"];
$section_search_rows = items(field($section_search_page, 'list_data'));
require_condition(equal(text(field($section_search_page, 'records_found')), text(count($section_search_rows))), 'records_found differs from this complete page\'s rows.');
require_condition(is_present(text(field($section_search_page, 'total_records'))), 'The search wrapper needs total_records.');
require_condition(either(equal(field($section_search_page, 'has_more'), true), equal(field($section_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.');
foreach (items($section_search_rows) as $section_search_row) {
require_condition(equal(text(field($section_search_row, 'event_id')), $setup_event_id), 'A section search row belongs to a different Event; stop before adopting or creating anything.');
if (equal(text(field($section_search_row, 'name')), $desired_section_name)) {
$section_search_candidate_id = positive_id(text(field($section_search_row, 'id')));
if (is_present($setup_section_id)) {
require_condition(equal($setup_section_id, $section_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.');
}
$setup_section_id = $section_search_candidate_id;
}
}
if (equal(field($section_search_page, 'has_more'), false)) {
break;
}
require_condition(not_value(is_empty($section_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.');
$section_search_offset = add_offset($section_search_offset, count($section_search_rows));
}
if (not_value(is_present($setup_section_id))) {
$section_write_fingerprint = journal_fingerprint((object)['event_id' => $setup_event_id, 'name' => $desired_section_name]);
$section_intent = journal_begin($setup_job, 'create_section', 'POST', '/v1/tasks/sections', $section_write_fingerprint);
$section_create_response = call('create_section', [], (object)['event_id' => $setup_event_id, 'name' => $desired_section_name], text(field($section_intent, 'idempotency_key')));
require_condition(equal(response_status($section_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$created_section = $section_create_response["body"];
$setup_section_id = positive_id(text(field($created_section, 'id')));
require_condition(equal(text(field($created_section, 'event_id')), $setup_event_id), 'The created Task Section belongs to a different Event; preserve the pending intent.');
$recorded_section_name = text(field($created_section, 'name'));
require_condition(is_present($recorded_section_name), 'The Task Section acknowledgement needs its actual saved name.');
journal_acknowledge($setup_job, 'create_section', (object)['id' => $setup_section_id, 'event_id' => $setup_event_id, 'name' => $recorded_section_name]);
}
}
$section_confirmation_response = call('confirm_section', ['id' => $setup_section_id], null, null);
require_condition(equal(response_status($section_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$confirmed_setup_section = $section_confirmation_response["body"];
require_condition(both(equal(text(field($confirmed_setup_section, 'id')), $setup_section_id), both(equal(text(field($confirmed_setup_section, 'event_id')), $setup_event_id), equal(text(field($confirmed_setup_section, 'name')), $recorded_section_name))), 'The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.');
if (not_value(journal_completed($setup_job, 'create_section'))) {
journal_adopt($setup_job, 'create_section', 'GET', '/v1/tasks/sections/info', (object)['event_id' => text(field($confirmed_setup_section, 'event_id')), 'id' => text(field($confirmed_setup_section, 'id')), 'name' => text(field($confirmed_setup_section, 'name'))]);
}
$setup_dates_response = call('read_dates', ['event_id' => $setup_event_id, 'filter_by_date_type_id' => '1', '$include_record_revision' => 'true'], null, null);
require_condition(equal(response_status($setup_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$setup_dates_page = $setup_dates_response["body"];
require_condition(both(equal(text(field($setup_dates_page, 'records_found')), '1'), both(equal(text(field($setup_dates_page, 'total_records')), '1'), equal(field($setup_dates_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.');
$setup_dates_group = single(field($setup_dates_page, 'list_data'));
require_condition(both(equal(text(field($setup_dates_group, 'event_id')), $setup_event_id), equal(text(field($setup_dates_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.');
$setup_dates_revision = text(field($setup_dates_group, 'record_revision'));
require_condition(is_present($setup_dates_revision), 'Read the actual selected group revision before replacing it.');
if (journal_completed($setup_job, 'save_dates')) {
$recorded_dates = journal_recorded($setup_job, 'save_dates');
require_condition(both(equal(text(field($recorded_dates, 'event_id')), $setup_event_id), equal(text(field($recorded_dates, 'date_type_id')), '1')), 'The recorded Dates acknowledgement belongs to another Event or group.');
} else {
$setup_dates_fingerprint = journal_fingerprint((object)['event_id' => $setup_event_id, 'date_type_id' => '1', 'dates' => $desired_dates_json, 'expected_revision' => $setup_dates_revision]);
journal_begin($setup_job, 'save_dates', 'PATCH', '/v1/events/dates', $setup_dates_fingerprint);
$setup_dates_save_response = call('save_dates', [], (object)['event_id' => $setup_event_id, 'date_type_id' => '1', 'dates' => $desired_setup_dates, 'expected_revision' => $setup_dates_revision], null);
require_condition(equal(response_status($setup_dates_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$setup_dates_ack = $setup_dates_save_response["body"];
$setup_dates_saved_revision = text(field($setup_dates_ack, 'record_revision'));
require_condition(is_present($setup_dates_saved_revision), 'The checked Dates save needs its actual returned revision.');
journal_acknowledge($setup_job, 'save_dates', (object)['event_id' => $setup_event_id, 'date_type_id' => '1', 'record_revision' => $setup_dates_saved_revision]);
}
$setup_dates_verify_response = call('verify_dates', ['event_id' => $setup_event_id, 'filter_by_date_type_id' => '1'], null, null);
require_condition(equal(response_status($setup_dates_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$setup_dates_verify_page = $setup_dates_verify_response["body"];
require_condition(both(equal(text(field($setup_dates_verify_page, 'records_found')), '1'), both(equal(text(field($setup_dates_verify_page, 'total_records')), '1'), equal(field($setup_dates_verify_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.');
$setup_dates_verify_group = single(field($setup_dates_verify_page, 'list_data'));
require_condition(both(equal(text(field($setup_dates_verify_group, 'event_id')), $setup_event_id), equal(text(field($setup_dates_verify_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.');
require_condition(deep_equal(field($setup_dates_verify_group, 'dates'), $desired_setup_dates), 'The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.');
$setup_event_readback_response = call('event_readback', ['id' => $setup_event_id], null, null);
require_condition(equal(response_status($setup_event_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.');
$setup_event_readback = $setup_event_readback_response["body"];
require_condition(both(equal(text(field($setup_event_readback, 'id')), $setup_event_id), equal(text(field($setup_event_readback, 'integration_metadata_field_1')), $external_event_key)), 'Final Event readback is missing or rebound; earlier steps remain saved.');
require_condition(both(both(equal(text(field($setup_event_readback, 'name')), $desired_event_name), equal(text(field($setup_event_readback, 'start_date')), $desired_start_date)), equal(text(field($setup_event_readback, 'end_date')), $desired_end_date)), 'The Event name or main dates changed before final readback. Inspect the Event before starting another update.');
$planning_section_present = false;
foreach (items(items(field($setup_event_readback, 'task_sections'))) as $setup_event_section) {
if (equal(text(field($setup_event_section, 'id')), $setup_section_id)) {
$planning_section_present = true;
}
}
require_condition($planning_section_present, 'The Event\'s current Task Sections do not include the recorded section; inspect it rather than creating another.');
print_value((object)['event_id' => $setup_event_id, 'task_section_id' => $setup_section_id, 'dates_verified' => 'true']);
} finally {
$setup_job->close();
}
}
if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) main();
# Ruby 3.1+; standard library only. Set EXHIBITDAY_API_KEY before running.
require 'net/http'
require 'json'
require 'uri'
require 'csv'
require 'fileutils'
require 'securerandom'
require 'date'
require 'time'
require 'timeout'
BASE = 'https://api.exhibitday.com/v1'
SPEC = JSON.parse('{"preserveNumbers":true,"requests":{"workspace_binding":{"method":"GET","path":"/references/workspace_info"},"find_existing":{"method":"GET","path":"/events"},"create_event":{"method":"POST","path":"/events"},"confirm_event":{"method":"GET","path":"/events/info"},"update_event":{"method":"PATCH","path":"/events"},"verify_event_update":{"method":"GET","path":"/events/info"},"find_section":{"method":"GET","path":"/tasks/sections"},"create_section":{"method":"POST","path":"/tasks/sections"},"confirm_section":{"method":"GET","path":"/tasks/sections/info"},"read_dates":{"method":"GET","path":"/events/dates"},"save_dates":{"method":"PATCH","path":"/events/dates"},"verify_dates":{"method":"GET","path":"/events/dates"},"event_readback":{"method":"GET","path":"/events/info"}}}')
API_KEY = ENV.fetch('EXHIBITDAY_API_KEY')
raise 'Use the API key as one ASCII header value without control characters' if API_KEY.each_codepoint.any?{|point|point<32||point>126}
def decode_json(text)
if SPEC.fetch('preserveNumbers')
# Preserve JSON NUMBER lexemes for CSV, without replacing digits inside JSON strings.
text = text.gsub(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/) do |token|
token.start_with?('"') ? token : JSON.generate(token)
end
end
JSON.parse(text)
end
def transport(method, url, headers, data)
uri = URI(url)
request_type = { 'GET' => Net::HTTP::Get, 'POST' => Net::HTTP::Post,
'PATCH' => Net::HTTP::Patch, 'DELETE' => Net::HTTP::Delete }.fetch(method)
request = request_type.new(uri.request_uri, headers)
request.body = data unless data.nil?
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
http.open_timeout = http.read_timeout = http.write_timeout = 30
http.max_retries = 0 # The outer loop owns the bounded retry policy.
response = http.start { |client| client.request(request) }
[response.code.to_i, response.body.to_s, response.each_header.to_h]
end
def retry_delay(headers, attempt)
value = headers['retry-after']
return 2**attempt if value.nil? || value.empty?
begin
[Float(value), 0].max
rescue ArgumentError, TypeError
begin
[Time.httpdate(value) - Time.now, 0].max
rescue ArgumentError
2**attempt
end
end
end
# An API error response. Branch on error_code (and status), never on the message text.
# uncertain is true when a PATCH or DELETE got no response or a server error: it may or may not have been applied.
class ApiError < RuntimeError
attr_reader :status, :error_code, :uncertain
def initialize(status, error_code, message, uncertain = false)
super(message)
@status = status
@error_code = error_code
@uncertain = uncertain
end
end
def call(name, params = {}, body = nil, key = nil)
route = SPEC.fetch('requests').fetch(name)
headers = { 'Authorization' => 'Bearer ' + API_KEY, 'Accept' => 'application/json' }
if route.fetch('method') == 'POST'
headers['Idempotency-Key'] = key || raise('Persist a logical create key before sending POST') # ONCE before retries.
end
data = body.nil? ? nil : JSON.generate(body)
headers['Content-Type'] = 'application/json' unless data.nil?
query = URI.encode_www_form(params)
url = BASE + route.fetch('path') + (query.empty? ? '' : '?' + query)
# Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
# server error is never resent blindly: it may already have been applied, so the caller reads the record first.
resend = route.fetch('method') == 'GET'
5.times do |attempt|
begin
status, raw, response_headers = transport(route.fetch('method'), url, headers, data)
rescue IOError, SystemCallError, Timeout::Error, SocketError
raise ApiError.new(0, nil, 'No response', true) unless resend
raise if attempt == 4
sleep(2**attempt)
next
end
response_headers = response_headers.transform_keys(&:downcase)
result = nil
unless status == 304 || raw.empty?
begin
result = decode_json(raw)
rescue JSON::ParserError, EncodingError
raise 'Expected a JSON success response' if status < 400
end
end
if status >= 500 && !resend
raise ApiError.new(status, result.is_a?(Hash) ? result['error_code'] : nil, "HTTP #{status}", true)
end
transient = resend && (status == 429 || (500..599).cover?(status))
if transient
raise 'Retry limit reached; check the outcome before starting a new create' if attempt == 4
sleep(retry_delay(response_headers, attempt))
next
end
if status >= 400
raise ApiError.new(status, nil, "HTTP #{status}") unless result.is_a?(Hash)
raise ApiError.new(status, result['error_code'], "#{result['error_code']} #{result['error_params'].inspect}: #{result['errors'].inspect} (request #{result['request_id']})")
end
return { status: status, body: result, headers: response_headers, raw: raw }
end
raise 'Retry limit reached'
end
def add_offset(offset,received)
result=Integer(offset)+received
raise "Cannot advance this int32 offset; reconcile the query" if received<=0 || result>2147483647
result.to_s
end
def both(left,right);left&&right;end
def items(value)
raise "Expected a JSON array" unless value.is_a?(Array)
value
end
def count(value)
items(value).length
end
def deep_equal(left,right)
return false unless left.class==right.class
if left.is_a?(Hash)
return left.keys.sort==right.keys.sort&&left.all?{|key,value|deep_equal(value,right[key])}
end
return left.length==right.length&&left.zip(right).all?{|a,b|deep_equal(a,b)} if left.is_a?(Array)
left==right
end
def either(left,right)
raise "Expected Boolean criteria" unless [true,false].include?(left) && [true,false].include?(right)
left || right
end
def equal(left,right)
left.class==right.class && left==right
end
def field(value,name)
raise "Missing response field: #{name}" unless value.is_a?(Hash) && value.key?(name)
value.fetch(name)
end
def is_empty(value)
count(value)==0
end
def is_present(value)
!value.nil? && value!=""
end
require 'digest'
require 'securerandom'
require 'uri'
# Private client restart state, with no transport or application dependency.
module GuideJournalProtocol
PREAMBLE="EXHIBITDAY-GUIDE-JOURNAL 1\n".b.freeze
class Refusal < StandardError; end
def self.utf8(value)
raise Refusal,'Journal fields are exact strings' unless value.is_a?(String)&&value.valid_encoding?
raw=value.encode(Encoding::UTF_8)
raise Refusal,'Invalid UTF8 journal field' unless raw.valid_encoding?
raw.b
end
def self.strings(values)
values.map{|value|raw=utf8(value);raw.bytesize.to_s.b+':'.b+raw}.join.b
end
def self.read_strings(raw)
values=[];offset=0
while offset<raw.bytesize
ending=raw.index(':'.b,offset);raise Refusal,'Incomplete string length' unless ending
length=raw.byteslice(offset,ending-offset);raise Refusal,'Noncanonical string length' unless length.match?(/\A(?:0|[1-9][0-9]*)\z/)
size=length.to_i;offset=ending+1;raise Refusal,'Incomplete journal string' if size>raw.bytesize-offset
value=raw.byteslice(offset,size).dup.force_encoding(Encoding::UTF_8);raise Refusal,'Invalid UTF8 string' unless value.valid_encoding?
values<<value;offset+=size
end
values
end
def self.digest(raw);Digest::SHA256.hexdigest(raw).upcase;end
def self.fingerprint(pairs)
values=[];pairs.keys.sort.each do|name|
raise Refusal,'Use explicit secret-free fingerprint names' unless name.is_a?(String)&&name.match?(/\A[A-Za-z0-9_.-]+\z/)&&!['api_key','exhibitday_api_key'].include?(name.downcase)
values.concat([name,pairs.fetch(name)])
end
digest(strings(values))
end
def self.frame(values)
raw=strings(values);raw.bytesize.to_s.b+' '.b+digest(raw).b+"\n".b+raw+"\n".b
end
def self.decode(raw)
raw=raw.b;raise Refusal,'Unknown or incomplete journal version' unless raw.start_with?(PREAMBLE)
offset=PREAMBLE.bytesize;records=[]
while offset<raw.bytesize
ending=raw.index("\n".b,offset);raise Refusal,'Incomplete frame header; reconcile before retry' unless ending
header=raw.byteslice(offset,ending-offset);match=/\A(0|[1-9][0-9]*) ([0-9A-F]{64})\z/.match(header);raise Refusal,'Invalid frame header' unless match
size=match[1].to_i;offset=ending+1;raise Refusal,'Incomplete frame; reconcile before retry' if size>=raw.bytesize-offset
payload=raw.byteslice(offset,size);offset+=size
raise Refusal,'Journal integrity failed; reconcile before retry' unless raw.getbyte(offset)==10&&digest(payload)==match[2]
records<<read_strings(payload);offset+=1
end
records
end
def self.write_all(file,raw)
offset=0
while offset<raw.bytesize
written=file.syswrite(raw.byteslice(offset,raw.bytesize-offset));raise IOError,'Journal write did not advance' unless written&&written>0
offset+=written
end
file.flush;file.fsync
end
end
class GuideJournal
P=GuideJournalProtocol
def initialize(path,base,workspace,slug,job,input_fingerprint,writes,mode='resume')
@path=path.dup;@lock_path=path+'.lock';@file=nil;@owned=false;@tainted=false;@intents={};@saved={};@adopted={};@allowed={}
address=URI(base)
raise P::Refusal,'Use actual API base and closed guide slug' unless ['https','http'].include?(address.scheme)&&address.host&&address.userinfo.nil?&&address.query.nil?&&address.fragment.nil?&&slug.match?(/\A[a-z][a-z0-9-]*\z/)
raise P::Refusal,'Use actual workspace, stable explicit job ID and exact fingerprint' unless !job.strip.empty?&&workspace.match?(/\A[1-9][0-9]*\z/)&&input_fingerprint.match?(/\A[0-9A-F]{64}\z/)
raise P::Refusal,'Choose new or resume for this local job' unless ['new','resume'].include?(mode)
manifest=[]
writes.each do|step,method,route|
raise P::Refusal,'Use closed unique write manifest' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@allowed.key?(step)&&['POST','PATCH','DELETE'].include?(method)&&route.match?(/\A\/v1\/[A-Za-z0-9_\/-]+\z/)&&!route.include?('//')
@allowed[step.dup.freeze]=[method.dup.freeze,route.dup.freeze].freeze;manifest.concat([step,method,route])
end
raise P::Refusal,'Only write workflows need a restart journal' if @allowed.empty?
@header=['H','1',base,workspace,slug,job,input_fingerprint,P.digest(P.strings(manifest))].map{|value|value.dup.freeze}.freeze;P.strings(@header)
begin
@file=File.open(@lock_path,File::RDWR|File::CREAT|File::EXCL,0o600);@file.binmode;@owned=true
rescue Errno::EEXIST
raise P::Refusal,'This journal is locked; do not overlap jobs or steal a stale lock'
end
begin
@owner=SecureRandom.hex(16).freeze;P.write_all(@file,@owner.b);@identity=@file.stat
# Ruby's Windows fstat reports dev=0 while lstat reports the drive number.
# Both expose the same exact inode. Retain it plus the initial path device;
# compare like-for-like instead of treating the differing dev APIs as equal.
named_identity=File.lstat(@lock_path);raise P::Refusal,'Lock identity did not bind' unless named_identity.ino==@identity.ino
@path_device=named_identity.dev
raise P::Refusal,'Choose a private regular journal file' if File.symlink?(@path)
raise P::Refusal,'Journal missing: stop and reconcile lost state before starting a new logical job' if mode=='resume'&&!File.exist?(@path)
raise P::Refusal,'Journal exists; use resume for the same logical job' if mode=='new'&&File.exist?(@path)
if mode=='new'
File.open(@path,File::WRONLY|File::CREAT|File::EXCL,0o600){|target|target.binmode;P.write_all(target,P::PREAMBLE+P.frame(@header))}
end
records=P.decode(File.binread(@path));raise P::Refusal,'Journal workspace/base/guide/job/input binding differs' if records.empty?||records[0]!=@header
records.drop(1).each{|record|apply(record)}
raise P::Refusal,'Saved intent lacks ACK; stop and reconcile before retry' if @intents.keys.any?{|step|!@saved.key?(step)}
rescue Exception
close;raise
end
end
def apply(record)
case record[0]
when 'I'
raise P::Refusal,'Invalid intent shape' unless record.length==6
_,step,method,route,fingerprint,key=record
raise P::Refusal,'Invalid, future or repeated intent' unless step.match?(/\A[a-z][a-z0-9_-]*\z/)&&!@intents.key?(step)&&!@adopted.key?(step)&&@allowed[step]==[method,route]&&fingerprint.match?(/\A[0-9A-F]{64}\z/)&&!@intents.keys.any?{|name|!@saved.key?(name)}
raise P::Refusal,'Invalid persisted action key' unless (method=='POST'&&key.match?(/\A[0-9a-f]{32}\z/))||(method!='POST'&&key=='')
@intents[step.dup.freeze]={'method'=>method.dup.freeze,'path'=>route.dup.freeze,'request_fingerprint'=>fingerprint.dup.freeze,'idempotency_key'=>key.dup.freeze}.freeze
when 'A'
raise P::Refusal,'Invalid ACK shape' unless record.length>=3
_,step,count,*pairs=record
raise P::Refusal,'ACK without exactly one prior intent' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i&&@intents.key?(step)&&!@saved.key?(step)
names=pairs.each_slice(2).map(&:first)
raise P::Refusal,'ACK fields must be unique sorted secret-free identifiers' unless names==names.uniq.sort&&names.all?{|name|name.match?(/\A[a-z][a-z0-9_]*\z/)&&!['api_key','exhibitday_api_key'].include?(name)}
@saved[step.dup.freeze]=pairs.each_slice(2).to_h.transform_values{|value|value.dup.freeze}.freeze
when 'S'
raise P::Refusal,'Invalid read-adoption shape' unless record.length>=6
_,step,method,route,read_fingerprint,count,*pairs=record
completed=(@saved.keys+@adopted.keys).uniq;order=@allowed.keys
raise P::Refusal,'Adopt only the exact next setup action without any pending intent' unless completed.length<order.length&&completed.sort==order.take(completed.length).sort&&step==order[completed.length]&&!@intents.keys.any?{|name|!@saved.key?(name)}
target=@allowed[step];expected=(target==['POST','/v1/events'] || step=='update_event' && target==['PATCH','/v1/events']) ? '/v1/events/info' : target==['POST','/v1/tasks/sections'] ? '/v1/tasks/sections/info' : nil
raise P::Refusal,'Adoption requires the exact source-bound single Event or section read' unless method=='GET'&&expected&&route==expected
raise P::Refusal,'Invalid read-adoption field count' unless count.match?(/\A(?:0|[1-9][0-9]*)\z/)&&pairs.length==2*count.to_i
names=pairs.each_slice(2).map(&:first);fields=expected=='/v1/events/info' ? ['id','integration_metadata_field_1'] : ['event_id','id','name']
raise P::Refusal,'Read-adoption fields must match the exact source tuple' unless names==fields
saved=pairs.each_slice(2).to_h
['id','event_id'].each{|name|raise P::Refusal,'Read-adoption IDs must be exact positive Int64 strings' if saved.key?(name)&&(!saved[name].match?(/\A[1-9][0-9]*\z/)||saved[name].to_i>9223372036854775807)}
raise P::Refusal,'Read-adoption material must be complete and fingerprint-bound' if fields.any?{|name|!['id','event_id'].include?(name)&&saved[name].empty?}||read_fingerprint!=P.fingerprint(saved)
@adopted[step.dup.freeze]=saved.transform_values{|value|value.dup.freeze}.freeze
else
raise P::Refusal,'Unknown journal transition'
end
end
def require_active
raise P::Refusal,'Journal is closed or IO outcome needs reconciliation' unless @owned&&@file&&!@tainted
current=File.lstat(@lock_path)
raise P::Refusal,'Journal lock replaced; stop without deleting it' unless current.dev==@path_device&¤t.ino==@identity.ino&&File.binread(@lock_path)==@owner.b
end
def append(record)
require_active;raw=P.frame(record)
begin
File.open(@path,'ab'){|target|P.write_all(target,raw)}
rescue Exception
@tainted=true;raise
end
end
def acknowledged(step);require_active;@saved.key?(step);end
def saved(step)
require_active;raise P::Refusal,'No acknowledged state exists' unless @saved.key?(step)
@saved.fetch(step).transform_values(&:dup)
end
def completed(step);require_active;@saved.key?(step)||@adopted.key?(step);end
def adopted(step);require_active;@adopted.key?(step);end
def recorded(step);require_active;raise P::Refusal,'No completed write or read-adoption exists' unless completed(step);(@saved[step]||@adopted[step]).transform_values(&:dup);end
def adopt(step,method,route,saved)
require_active;record=['S',step,method,route,P.fingerprint(saved),saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved[name]])};previous=@adopted.dup
begin;apply(record);P.strings(record);ensure;@adopted=previous;end
append(record);apply(record)
end
def begin_action(step,method,route,request_fingerprint)
require_active;raise P::Refusal,'Never blindly repeat an action' if @intents.key?(step)
record=['I',step,method,route,request_fingerprint,method=='POST'?SecureRandom.hex(16):'']
previous=@intents.dup;begin;apply(record);ensure;@intents=previous;end
append(record);apply(record);@intents.fetch(step).transform_values(&:dup)
end
def acknowledge(step,saved)
require_active;record=['A',step,saved.length.to_s];saved.keys.sort.each{|name|record.concat([name,saved.fetch(name)])}
previous=@saved.dup;begin;apply(record);P.strings(record);ensure;@saved=previous;end
append(record);apply(record)
end
def close
return unless @owned
if @tainted;@file.close;@file=nil;@owned=false;return;end
begin;require_active;rescue Exception;@file.close;@file=nil;@owned=false;raise;end
@file.close;@file=nil;@owned=false;File.unlink(@lock_path)
end
end
def journal_values(value)
raise GuideJournalProtocol::Refusal,'Saved/fingerprint values must be exact strings' unless value.is_a?(Hash)&&value.all?{|name,item|name.is_a?(String)&&item.is_a?(String)}
value.transform_values(&:dup)
end
def journal_acknowledge(job,step,saved);job.acknowledge(step,journal_values(saved));end
def journal_acknowledged(job,step);job.acknowledged(step);end
def journal_adopt(job,step,method,path,saved);job.adopt(step,method,path,journal_values(saved));end
def journal_begin(job,step,method,path,request_fingerprint);job.begin_action(step,method,path,request_fingerprint);end
def journal_completed(job,step);job.completed(step);end
def journal_fingerprint(value);GuideJournalProtocol.fingerprint(journal_values(value));end
def journal_recorded(job,step);job.recorded(step);end
def not_value(value)
raise "Expected a Boolean" unless value==true || value==false
!value
end
def open_journal(path,base,workspace,slug,job,input_fingerprint,writes,mode);GuideJournal.new(path,base,workspace,slug,job,input_fingerprint,writes,mode);end
def optional(name,fallback)
value=ENV[name]
value.nil? || value.empty? ? fallback : value
end
def page_size(value)
raise "Page size must be a positive int32" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=2147483647
value
end
class WorkflowInputObject<Hash
def []=(key,value);raise'Duplicate JSON input property' if key?(key);super;end
end
def parse_json(value)
result=JSON.parse(value,object_class:WorkflowInputObject,allow_nan:false)
copy=nil;copy=->(node){case node;when Hash;node.each_with_object({}){|(key,item),memo|memo[key]=copy.call(item)};when Array;node.map{|item|copy.call(item)};when Float;raise'Use finite JSON numbers' unless node.finite?;node;else;node;end}
copy.call(result)
end
def positive_id(value)
raise "Use a positive record ID" unless /\A[1-9][0-9]*\z/.match?(value) && Integer(value)<=9223372036854775807
value
end
def print_value(value)
STDOUT.binmode.write((value.is_a?(String)?value:JSON.generate(value))+"\n")
end
def require_condition(value,message)
raise message unless value==true
end
def required(name)
value=ENV[name]
raise "Set #{name}" if value.nil? || value.strip.empty?
value
end
def response_status(value);value.fetch(:status).to_s;end
def single(value);rows=items(value);raise 'Expected exactly one selected record' unless rows.length==1;rows[0];end
def text(value)
return "" if value.nil?
return value.to_s if value.is_a?(String)||value.is_a?(Integer)||value==true||value==false
raise "Expected a scalar response value"
end
def validate_crm_event_inputs(key, name, start_date, end_date)
boundary = /\A[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]\z/
[[name,'EXHIBITDAY_EVENT_NAME',500],[key,'EXHIBITDAY_EXTERNAL_EVENT_KEY',3000]].each do |value,label,limit|
GuideJournalProtocol.utf8(value)
raise GuideJournalProtocol::Refusal,'Remove whitespace at the start or end of '+label if value.empty? || boundary.match?(value)
raise GuideJournalProtocol::Refusal,label+" exceeds #{limit} UTF-16 code units" if value.encode('UTF-16LE').bytesize / 2 > limit
end
if name.match?(/[<>\r\n]/) || name.downcase == 'null'
raise GuideJournalProtocol::Refusal,'Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null'
end
[[start_date,'EXHIBITDAY_START_DATE'],[end_date,'EXHIBITDAY_END_DATE']].each do |value,label|
match = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/.match(value)
unless match && match[1].to_i >= 1753 && Date.valid_date?(*match.captures.map(&:to_i))
raise GuideJournalProtocol::Refusal,label+' must be a calendar date in YYYY-MM-DD on or after 1753-01-01'
end
end
raise GuideJournalProtocol::Refusal,'EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE' if end_date < start_date
end
def main
external_event_key = required('EXHIBITDAY_EXTERNAL_EVENT_KEY')
desired_event_name = required('EXHIBITDAY_EVENT_NAME')
desired_start_date = required('EXHIBITDAY_START_DATE')
desired_end_date = required('EXHIBITDAY_END_DATE')
desired_dates_json = required('EXHIBITDAY_EXHIBIT_DATES_JSON')
desired_section_name = optional('EXHIBITDAY_TASK_SECTION_NAME', 'Pre-event planning')
setup_page_size = page_size(optional('EXHIBITDAY_PAGE_SIZE', '100'))
desired_setup_dates = items(parse_json(desired_dates_json))
validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date)
journal_path = required('EXHIBITDAY_JOURNAL')
stable_job_id = required('EXHIBITDAY_JOB_ID')
job_mode = optional('EXHIBITDAY_JOB_MODE', 'resume')
setup_workspace_response = call('workspace_binding', {}, nil, nil)
require_condition(equal(response_status(setup_workspace_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
setup_workspace = setup_workspace_response.fetch(:body)
owned_workspace_id = positive_id(text(field(setup_workspace, 'id')))
setup_input_fingerprint = journal_fingerprint({'workflow_contract_sha256' => '19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32', 'external_event_key' => external_event_key, 'name' => desired_event_name, 'start_date' => desired_start_date, 'end_date' => desired_end_date, 'section_name' => desired_section_name, 'dates' => desired_dates_json})
setup_job = open_journal(journal_path, 'https://api.exhibitday.com/v1', owned_workspace_id, 'event-setup-crm', stable_job_id, setup_input_fingerprint, [['create_event', 'POST', '/v1/events'], ['update_event', 'PATCH', '/v1/events'], ['create_section', 'POST', '/v1/tasks/sections'], ['save_dates', 'PATCH', '/v1/events/dates']], job_mode)
begin
setup_event_id = ''
setup_section_id = ''
recorded_section_name = desired_section_name
if journal_completed(setup_job, 'create_event')
recorded_event = journal_recorded(setup_job, 'create_event')
setup_event_id = positive_id(text(field(recorded_event, 'id')))
require_condition(equal(text(field(recorded_event, 'integration_metadata_field_1')), external_event_key), 'The journal\'s completed Event differs from this external key.')
else
event_search_offset = '0'
event_search_query = {'filter_by_integration_metadata_field_1' => external_event_key, '$limit' => setup_page_size}
while true
event_search_query['$offset'] = event_search_offset
event_search_response = call('find_existing', event_search_query, nil, nil)
require_condition(equal(response_status(event_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
event_search_page = event_search_response.fetch(:body)
event_search_rows = items(field(event_search_page, 'list_data'))
require_condition(equal(text(field(event_search_page, 'records_found')), text(count(event_search_rows))), 'records_found differs from this complete page\'s rows.')
require_condition(is_present(text(field(event_search_page, 'total_records'))), 'The search wrapper needs total_records.')
require_condition(either(equal(field(event_search_page, 'has_more'), true), equal(field(event_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.')
items(event_search_rows).each do |event_search_row|
if equal(text(field(event_search_row, 'integration_metadata_field_1')), external_event_key)
event_search_candidate_id = positive_id(text(field(event_search_row, 'id')))
if is_present(setup_event_id)
require_condition(equal(setup_event_id, event_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.')
end
setup_event_id = event_search_candidate_id
end
end
if equal(field(event_search_page, 'has_more'), false)
break
end
require_condition(not_value(is_empty(event_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.')
event_search_offset = add_offset(event_search_offset, count(event_search_rows))
end
if not_value(is_present(setup_event_id))
event_write_fingerprint = journal_fingerprint({'name' => desired_event_name, 'start_date' => desired_start_date, 'end_date' => desired_end_date, 'integration_metadata_field_1' => external_event_key})
event_intent = journal_begin(setup_job, 'create_event', 'POST', '/v1/events', event_write_fingerprint)
event_create_response = call('create_event', {}, {'name' => desired_event_name, 'start_date' => desired_start_date, 'end_date' => desired_end_date, 'integration_metadata_field_1' => external_event_key}, text(field(event_intent, 'idempotency_key')))
require_condition(equal(response_status(event_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
created_event = event_create_response.fetch(:body)
setup_event_id = positive_id(text(field(created_event, 'id')))
require_condition(equal(text(field(created_event, 'integration_metadata_field_1')), external_event_key), 'The created Event\'s external key differs; preserve the pending intent and reconcile.')
require_condition(both(is_present(text(field(created_event, 'name'))), both(is_present(text(field(created_event, 'start_date'))), is_present(text(field(created_event, 'end_date'))))), 'The Event acknowledgement omitted its saved name or main dates.')
journal_acknowledge(setup_job, 'create_event', {'id' => setup_event_id, 'integration_metadata_field_1' => external_event_key})
end
end
event_confirmation_response = call('confirm_event', {'id' => setup_event_id, '$include_record_revision' => 'true'}, nil, nil)
require_condition(equal(response_status(event_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
confirmed_setup_event = event_confirmation_response.fetch(:body)
require_condition(both(equal(text(field(confirmed_setup_event, 'id')), setup_event_id), equal(text(field(confirmed_setup_event, 'integration_metadata_field_1')), external_event_key)), 'The captured Event is missing or rebound; stop instead of searching for or creating a replacement.')
if not_value(journal_completed(setup_job, 'create_event'))
journal_adopt(setup_job, 'create_event', 'GET', '/v1/events/info', {'id' => text(field(confirmed_setup_event, 'id')), 'integration_metadata_field_1' => text(field(confirmed_setup_event, 'integration_metadata_field_1'))})
end
setup_event_revision = text(field(confirmed_setup_event, 'record_revision'))
require_condition(is_present(setup_event_revision), 'Read the selected Event with its revision before comparing or updating it.')
require_condition(both(both(is_present(text(field(confirmed_setup_event, 'name'))), is_present(text(field(confirmed_setup_event, 'start_date')))), is_present(text(field(confirmed_setup_event, 'end_date')))), 'The selected Event must return its current name, start date and end date.')
if journal_completed(setup_job, 'update_event')
recorded_event_update = journal_recorded(setup_job, 'update_event')
require_condition(both(equal(text(field(recorded_event_update, 'id')), setup_event_id), equal(text(field(recorded_event_update, 'integration_metadata_field_1')), external_event_key)), 'The recorded Event update has a different identity. Stop and reconcile.')
require_condition(both(both(equal(text(field(confirmed_setup_event, 'name')), desired_event_name), equal(text(field(confirmed_setup_event, 'start_date')), desired_start_date)), equal(text(field(confirmed_setup_event, 'end_date')), desired_end_date)), 'The Event name or main dates changed after this job checked them. Review the current Event before writing again.')
else
if both(both(equal(text(field(confirmed_setup_event, 'name')), desired_event_name), equal(text(field(confirmed_setup_event, 'start_date')), desired_start_date)), equal(text(field(confirmed_setup_event, 'end_date')), desired_end_date))
journal_adopt(setup_job, 'update_event', 'GET', '/v1/events/info', {'id' => setup_event_id, 'integration_metadata_field_1' => external_event_key})
else
require_condition(not_value(journal_acknowledged(setup_job, 'create_event')), 'The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.')
event_update_body = {'id' => setup_event_id, 'expected_revision' => setup_event_revision}
if not_value(equal(text(field(confirmed_setup_event, 'name')), desired_event_name))
event_update_body['name'] = desired_event_name
end
if not_value(equal(text(field(confirmed_setup_event, 'start_date')), desired_start_date))
event_update_body['start_date'] = desired_start_date
end
if not_value(equal(text(field(confirmed_setup_event, 'end_date')), desired_end_date))
event_update_body['end_date'] = desired_end_date
end
event_update_fingerprint = journal_fingerprint(event_update_body)
journal_begin(setup_job, 'update_event', 'PATCH', '/v1/events', event_update_fingerprint)
event_update_response = call('update_event', {}, event_update_body, nil)
require_condition(equal(response_status(event_update_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
event_update_ack = event_update_response.fetch(:body)
event_updated_revision = text(field(event_update_ack, 'record_revision'))
require_condition(is_present(event_updated_revision), 'The conditional Event update needs its returned revision. Reconcile the pending request before continuing.')
journal_acknowledge(setup_job, 'update_event', {'id' => setup_event_id, 'integration_metadata_field_1' => external_event_key, 'record_revision' => event_updated_revision})
end
end
event_update_verify_response = call('verify_event_update', {'id' => setup_event_id}, nil, nil)
require_condition(equal(response_status(event_update_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
verified_setup_event = event_update_verify_response.fetch(:body)
require_condition(both(both(equal(text(field(verified_setup_event, 'id')), setup_event_id), equal(text(field(verified_setup_event, 'integration_metadata_field_1')), external_event_key)), both(both(equal(text(field(verified_setup_event, 'name')), desired_event_name), equal(text(field(verified_setup_event, 'start_date')), desired_start_date)), equal(text(field(verified_setup_event, 'end_date')), desired_end_date))), 'The Event\'s current identity, name or main dates differ. Inspect the Event before continuing with setup.')
if journal_completed(setup_job, 'create_section')
recorded_section = journal_recorded(setup_job, 'create_section')
setup_section_id = positive_id(text(field(recorded_section, 'id')))
require_condition(equal(text(field(recorded_section, 'event_id')), setup_event_id), 'The recorded Task Section belongs to a different Event.')
recorded_section_name = text(field(recorded_section, 'name'))
else
section_search_offset = '0'
section_search_query = {'filter_by_event_id' => setup_event_id, '$limit' => setup_page_size}
while true
section_search_query['$offset'] = section_search_offset
section_search_response = call('find_section', section_search_query, nil, nil)
require_condition(equal(response_status(section_search_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
section_search_page = section_search_response.fetch(:body)
section_search_rows = items(field(section_search_page, 'list_data'))
require_condition(equal(text(field(section_search_page, 'records_found')), text(count(section_search_rows))), 'records_found differs from this complete page\'s rows.')
require_condition(is_present(text(field(section_search_page, 'total_records'))), 'The search wrapper needs total_records.')
require_condition(either(equal(field(section_search_page, 'has_more'), true), equal(field(section_search_page, 'has_more'), false)), 'Expected a Boolean has_more value.')
items(section_search_rows).each do |section_search_row|
require_condition(equal(text(field(section_search_row, 'event_id')), setup_event_id), 'A section search row belongs to a different Event; stop before adopting or creating anything.')
if equal(text(field(section_search_row, 'name')), desired_section_name)
section_search_candidate_id = positive_id(text(field(section_search_row, 'id')))
if is_present(setup_section_id)
require_condition(equal(setup_section_id, section_search_candidate_id), 'More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.')
end
setup_section_id = section_search_candidate_id
end
end
if equal(field(section_search_page, 'has_more'), false)
break
end
require_condition(not_value(is_empty(section_search_rows)), 'An empty search page has has_more=true. Stop and reconcile the search.')
section_search_offset = add_offset(section_search_offset, count(section_search_rows))
end
if not_value(is_present(setup_section_id))
section_write_fingerprint = journal_fingerprint({'event_id' => setup_event_id, 'name' => desired_section_name})
section_intent = journal_begin(setup_job, 'create_section', 'POST', '/v1/tasks/sections', section_write_fingerprint)
section_create_response = call('create_section', {}, {'event_id' => setup_event_id, 'name' => desired_section_name}, text(field(section_intent, 'idempotency_key')))
require_condition(equal(response_status(section_create_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
created_section = section_create_response.fetch(:body)
setup_section_id = positive_id(text(field(created_section, 'id')))
require_condition(equal(text(field(created_section, 'event_id')), setup_event_id), 'The created Task Section belongs to a different Event; preserve the pending intent.')
recorded_section_name = text(field(created_section, 'name'))
require_condition(is_present(recorded_section_name), 'The Task Section acknowledgement needs its actual saved name.')
journal_acknowledge(setup_job, 'create_section', {'id' => setup_section_id, 'event_id' => setup_event_id, 'name' => recorded_section_name})
end
end
section_confirmation_response = call('confirm_section', {'id' => setup_section_id}, nil, nil)
require_condition(equal(response_status(section_confirmation_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
confirmed_setup_section = section_confirmation_response.fetch(:body)
require_condition(both(equal(text(field(confirmed_setup_section, 'id')), setup_section_id), both(equal(text(field(confirmed_setup_section, 'event_id')), setup_event_id), equal(text(field(confirmed_setup_section, 'name')), recorded_section_name))), 'The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.')
if not_value(journal_completed(setup_job, 'create_section'))
journal_adopt(setup_job, 'create_section', 'GET', '/v1/tasks/sections/info', {'event_id' => text(field(confirmed_setup_section, 'event_id')), 'id' => text(field(confirmed_setup_section, 'id')), 'name' => text(field(confirmed_setup_section, 'name'))})
end
setup_dates_response = call('read_dates', {'event_id' => setup_event_id, 'filter_by_date_type_id' => '1', '$include_record_revision' => 'true'}, nil, nil)
require_condition(equal(response_status(setup_dates_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
setup_dates_page = setup_dates_response.fetch(:body)
require_condition(both(equal(text(field(setup_dates_page, 'records_found')), '1'), both(equal(text(field(setup_dates_page, 'total_records')), '1'), equal(field(setup_dates_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.')
setup_dates_group = single(field(setup_dates_page, 'list_data'))
require_condition(both(equal(text(field(setup_dates_group, 'event_id')), setup_event_id), equal(text(field(setup_dates_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.')
setup_dates_revision = text(field(setup_dates_group, 'record_revision'))
require_condition(is_present(setup_dates_revision), 'Read the actual selected group revision before replacing it.')
if journal_completed(setup_job, 'save_dates')
recorded_dates = journal_recorded(setup_job, 'save_dates')
require_condition(both(equal(text(field(recorded_dates, 'event_id')), setup_event_id), equal(text(field(recorded_dates, 'date_type_id')), '1')), 'The recorded Dates acknowledgement belongs to another Event or group.')
else
setup_dates_fingerprint = journal_fingerprint({'event_id' => setup_event_id, 'date_type_id' => '1', 'dates' => desired_dates_json, 'expected_revision' => setup_dates_revision})
journal_begin(setup_job, 'save_dates', 'PATCH', '/v1/events/dates', setup_dates_fingerprint)
setup_dates_save_response = call('save_dates', {}, {'event_id' => setup_event_id, 'date_type_id' => '1', 'dates' => desired_setup_dates, 'expected_revision' => setup_dates_revision}, nil)
require_condition(equal(response_status(setup_dates_save_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
setup_dates_ack = setup_dates_save_response.fetch(:body)
setup_dates_saved_revision = text(field(setup_dates_ack, 'record_revision'))
require_condition(is_present(setup_dates_saved_revision), 'The checked Dates save needs its actual returned revision.')
journal_acknowledge(setup_job, 'save_dates', {'event_id' => setup_event_id, 'date_type_id' => '1', 'record_revision' => setup_dates_saved_revision})
end
setup_dates_verify_response = call('verify_dates', {'event_id' => setup_event_id, 'filter_by_date_type_id' => '1'}, nil, nil)
require_condition(equal(response_status(setup_dates_verify_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
setup_dates_verify_page = setup_dates_verify_response.fetch(:body)
require_condition(both(equal(text(field(setup_dates_verify_page, 'records_found')), '1'), both(equal(text(field(setup_dates_verify_page, 'total_records')), '1'), equal(field(setup_dates_verify_page, 'has_more'), false))), 'Expected one complete selected Dates group, without another page.')
setup_dates_verify_group = single(field(setup_dates_verify_page, 'list_data'))
require_condition(both(equal(text(field(setup_dates_verify_group, 'event_id')), setup_event_id), equal(text(field(setup_dates_verify_group, 'date_type_id')), '1')), 'The Dates group belongs to another Event or type.')
require_condition(deep_equal(field(setup_dates_verify_group, 'dates'), desired_setup_dates), 'The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.')
setup_event_readback_response = call('event_readback', {'id' => setup_event_id}, nil, nil)
require_condition(equal(response_status(setup_event_readback_response), '200'), 'Expected the endpoint\'s documented HTTP200 response; do not infer an acknowledgement from another status.')
setup_event_readback = setup_event_readback_response.fetch(:body)
require_condition(both(equal(text(field(setup_event_readback, 'id')), setup_event_id), equal(text(field(setup_event_readback, 'integration_metadata_field_1')), external_event_key)), 'Final Event readback is missing or rebound; earlier steps remain saved.')
require_condition(both(both(equal(text(field(setup_event_readback, 'name')), desired_event_name), equal(text(field(setup_event_readback, 'start_date')), desired_start_date)), equal(text(field(setup_event_readback, 'end_date')), desired_end_date)), 'The Event name or main dates changed before final readback. Inspect the Event before starting another update.')
planning_section_present = false
items(items(field(setup_event_readback, 'task_sections'))).each do |setup_event_section|
if equal(text(field(setup_event_section, 'id')), setup_section_id)
planning_section_present = true
end
end
require_condition(planning_section_present, 'The Event\'s current Task Sections do not include the recorded section; inspect it rather than creating another.')
print_value({'event_id' => setup_event_id, 'task_section_id' => setup_section_id, 'dates_verified' => 'true'})
ensure
setup_job.close()
end
end
main if $PROGRAM_NAME == __FILE__
// Go 1.18+; standard library only. Set EXHIBITDAY_API_KEY.
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"regexp"
"sort"
"unicode/utf8"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const base = "https://api.exhibitday.com/v1"
const specification = "{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"find_existing\":{\"method\":\"GET\",\"path\":\"/events\"},\"create_event\":{\"method\":\"POST\",\"path\":\"/events\"},\"confirm_event\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"update_event\":{\"method\":\"PATCH\",\"path\":\"/events\"},\"verify_event_update\":{\"method\":\"GET\",\"path\":\"/events/info\"},\"find_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections\"},\"create_section\":{\"method\":\"POST\",\"path\":\"/tasks/sections\"},\"confirm_section\":{\"method\":\"GET\",\"path\":\"/tasks/sections/info\"},\"read_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"save_dates\":{\"method\":\"PATCH\",\"path\":\"/events/dates\"},\"verify_dates\":{\"method\":\"GET\",\"path\":\"/events/dates\"},\"event_readback\":{\"method\":\"GET\",\"path\":\"/events/info\"}}}"
var spec map[string]any
var apiKey string
var client = &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}
var send = client.Do
type result struct { status int; body any; headers http.Header; raw []byte }
// An API error response (raised with panic). Branch on code (and status), never on the message text.
// uncertain is true when a PATCH or DELETE got no response or a server error: it may or may not have been applied.
type apiError struct { status int; code string; message string; uncertain bool }
func (failure apiError) Error() string { return failure.message }
func required(name string) string {
value := os.Getenv(name); if strings.TrimSpace(value) == "" { panic("Set " + name) }; return value
}
func text(value any) string { if value == nil { return "" }; return fmt.Sprint(value) }
func object(value any) map[string]any { if value == nil { return map[string]any{} }; return value.(map[string]any) }
func array(value any) []any { if value == nil { return nil }; return value.([]any) }
func decode(raw []byte) (any, error) {
var value any
decoder := json.NewDecoder(bytes.NewReader(raw)); decoder.UseNumber() // keeps exact decimal tokens
err := decoder.Decode(&value); return value, err
}
func call(name string, query map[string]string, body any, key string) result {
route := object(object(spec["requests"])[name]); method := text(route["method"])
headers := map[string]string{"Authorization": "Bearer " + apiKey, "Accept": "application/json"}
if method == "POST" { if key == "" { panic("Persist a logical create key before sending POST") }; headers["Idempotency-Key"] = key } // before retry loop
var data []byte
if body != nil { var err error; data, err = json.Marshal(body); if err != nil { panic(err) }; headers["Content-Type"] = "application/json" }
values := url.Values{}; for k,v := range query { values.Set(k,v) }
address := base + text(route["path"]); if len(values) > 0 { address += "?" + values.Encode() }
// Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
// server error is never resent blindly: it may already have been applied, so the caller reads the record first.
resend := method == "GET"
for attempt := 0; attempt < 5; attempt++ {
request, err := http.NewRequest(method, address, bytes.NewReader(data)); if err != nil { panic(err) }
for k,v := range headers { request.Header.Set(k,v) }
response, err := send(request)
if err != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(err) }; time.Sleep(time.Second*time.Duration(1<<attempt)); continue }
raw, readErr := io.ReadAll(response.Body); response.Body.Close()
if readErr != nil { if !resend { panic(apiError{0, "", "No response", true}) }; if attempt == 4 { panic(readErr) }; time.Sleep(time.Second*time.Duration(1<<attempt)); continue }
var parsed any
if response.StatusCode != 304 && len(raw)>0 {
parsed, err = decode(raw)
if err != nil && response.StatusCode < 400 { panic("Expected a JSON success response") }
}
errorBody, _ := parsed.(map[string]any)
if response.StatusCode >= 500 && !resend { panic(apiError{response.StatusCode, text(errorBody["error_code"]), fmt.Sprintf("HTTP %d", response.StatusCode), true}) }
retry := resend && (response.StatusCode == 429 || response.StatusCode >= 500)
if retry {
if attempt == 4 { panic("Retry limit reached; check the outcome before starting a new create") }
seconds := float64(int64(1)<<attempt)
if value, err := strconv.ParseFloat(response.Header.Get("Retry-After"),64); err == nil && value >= 0 { seconds = value }
time.Sleep(time.Duration(seconds*float64(time.Second))); continue
}
if response.StatusCode >= 400 { panic(apiError{response.StatusCode, text(errorBody["error_code"]), fmt.Sprintf("HTTP %d: %v (request %v)",response.StatusCode,errorBody["error_code"],errorBody["request_id"]), false}) }
return result{response.StatusCode, parsed, response.Header, raw}
}
panic("Retry limit reached")
}
func add_offset(offset string,received int64)string{previous,err:=strconv.ParseInt(offset,10,32);if err!=nil||received<=0||received>2147483647-previous{panic("Cannot advance this int32 offset; reconcile the query")};return strconv.FormatInt(previous+received,10)}
func both(left,right bool)bool{return left&&right}
func items(value any)[]any{result,ok:=value.([]any);if !ok{panic("Expected a JSON array")};return result}
func count(value any)int64{return int64(len(items(value)))}
func deep_equal(left,right any)bool{a,e:=json.Marshal(left);if e!=nil{panic(e)};b,e:=json.Marshal(right);if e!=nil{panic(e)};return string(a)==string(b)}
func either(left,right bool)bool{return left||right}
func equal(left,right any)bool{switch a:=left.(type){case string:b,ok:=right.(string);return ok&&a==b;case bool:b,ok:=right.(bool);return ok&&a==b;case int64:b,ok:=right.(int64);return ok&&a==b};return left==nil&&right==nil}
func field(value any,name string)any{obj,ok:=value.(map[string]any);if !ok{panic("Missing response object")};item,found:=obj[name];if !found{panic("Missing response field: "+name)};return item}
func is_empty(value any)bool{return count(value)==0}
func is_present(value string)bool{return value!=""}
// Private client restart state only; no API transport or workflow interpreter.
const journalPreamble = "EXHIBITDAY-GUIDE-JOURNAL 1\n"
type journalRefusal struct{ message string }
func (e journalRefusal) Error() string { return e.message }
func journalNeed(ok bool, message string) { if !ok { panic(journalRefusal{message}) } }
func journalMatch(value, pattern string) bool { return regexp.MustCompile("\\A(?:"+pattern+")\\z").MatchString(value) }
func journalStrings(values []string) []byte {
var output bytes.Buffer
for _,value:=range values { journalNeed(utf8.ValidString(value),"Journal fields must be valid UTF8 strings"); output.WriteString(strconv.Itoa(len(value))+":");output.WriteString(value) }
return output.Bytes()
}
func journalReadStrings(raw []byte) []string {
values:=[]string{};offset:=0
for offset<len(raw) { relative:=bytes.IndexByte(raw[offset:],':');journalNeed(relative>=0,"Incomplete journal string length");end:=offset+relative;text:=string(raw[offset:end]);journalNeed(journalMatch(text,"0|[1-9][0-9]*"),"Noncanonical journal string length");size,err:=strconv.ParseUint(text,10,64);offset=end+1;journalNeed(err==nil&&size<=uint64(len(raw)-offset),"Incomplete journal string");count:=int(size);value:=string(raw[offset:offset+count]);journalNeed(utf8.ValidString(value),"Invalid UTF8 journal field");values=append(values,value);offset+=count }
return values
}
func journalDigest(raw []byte) string { hash:=sha256.Sum256(raw);return strings.ToUpper(hex.EncodeToString(hash[:])) }
func journalFingerprint(pairs map[string]string) string {
names:=make([]string,0,len(pairs));for name:=range pairs { names=append(names,name) };sort.Strings(names);values:=[]string{}
for _,name:=range names { lower:=strings.ToLower(name);journalNeed(journalMatch(name,"[A-Za-z0-9_.-]+")&&lower!="api_key"&&lower!="exhibitday_api_key","Use explicit secret-free fingerprint names");values=append(values,name,pairs[name]) }
return journalDigest(journalStrings(values))
}
func journalFrame(values []string) []byte { raw:=journalStrings(values);header:=[]byte(strconv.Itoa(len(raw))+" "+journalDigest(raw)+"\n");result:=append(header,raw...);return append(result,'\n') }
func journalDecode(raw []byte) [][]string {
journalNeed(bytes.HasPrefix(raw,[]byte(journalPreamble)),"Unknown or incomplete journal version");offset:=len(journalPreamble);records:=[][]string{}
for offset<len(raw) { relative:=bytes.IndexByte(raw[offset:],'\n');journalNeed(relative>=0,"Incomplete frame header; reconcile before retry");end:=offset+relative;header:=string(raw[offset:end]);journalNeed(journalMatch(header,"(0|[1-9][0-9]*) [0-9A-F]{64}"),"Invalid frame header");fields:=strings.Split(header," ");size,err:=strconv.ParseUint(fields[0],10,64);offset=end+1;journalNeed(err==nil&&size<uint64(len(raw)-offset),"Incomplete frame; reconcile before retry");count:=int(size);payload:=raw[offset:offset+count];offset+=count;journalNeed(raw[offset]=='\n'&&journalDigest(payload)==fields[1],"Journal integrity failed; reconcile before retry");records=append(records,journalReadStrings(payload));offset++ }
return records
}
func journalWriteAll(file *os.File, raw []byte) error {
for len(raw)>0 { count,err:=file.Write(raw);if err!=nil{return err};if count<=0{return io.ErrShortWrite};raw=raw[count:] }
return file.Sync()
}
func journalWriteFile(path string,flags int,raw []byte) (err error) {
file,err:=os.OpenFile(path,flags,0600);if err!=nil{return err};defer func(){closed:=file.Close();if err==nil{err=closed}}();return journalWriteAll(file,raw)
}
func journalCopy(source map[string]string) map[string]string { copy:=map[string]string{};for name,value:=range source{copy[name]=value};return copy }
func journalCopyStates(source map[string]map[string]string) map[string]map[string]string { copy:=map[string]map[string]string{};for name,value:=range source{copy[name]=journalCopy(value)};return copy }
type guideJournal struct {
path,lockPath,owner string
header []string
allowed map[string][2]string
intents,savedValues,adoptedValues map[string]map[string]string
order []string
file *os.File
identity os.FileInfo
owned,tainted bool
}
func openGuideJournal(path,base,workspace,slug,job,inputFingerprint string,writes [][3]string,modes ...string) (result *guideJournal) {
mode:="resume";journalNeed(len(modes)<=1,"Choose one local job mode");if len(modes)==1{mode=modes[0]};journalNeed(mode=="new"||mode=="resume","Choose new or resume for this local job")
address,err:=url.Parse(base);journalNeed(err==nil&&address.Hostname()!=""&&(address.Scheme=="https"||address.Scheme=="http")&&address.User==nil&&address.RawQuery==""&&address.Fragment==""&&journalMatch(slug,"[a-z][a-z0-9-]*"),"Use actual API base and closed guide slug")
journalNeed(strings.TrimSpace(job)!=""&&journalMatch(workspace,"[1-9][0-9]*")&&journalMatch(inputFingerprint,"[0-9A-F]{64}"),"Use actual workspace, stable explicit job ID and exact fingerprint")
j:=&guideJournal{path:path,lockPath:path+".lock",allowed:map[string][2]string{},intents:map[string]map[string]string{},savedValues:map[string]map[string]string{},adoptedValues:map[string]map[string]string{}}
manifest:=[]string{};for _,write:=range writes { step,method,route:=write[0],write[1],write[2];_,exists:=j.allowed[step];journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&(method=="POST"||method=="PATCH"||method=="DELETE")&&journalMatch(route,"/v1/[A-Za-z0-9_/-]+")&&!strings.Contains(route,"//"),"Use a closed unique write manifest");j.allowed[step]=[2]string{method,route};j.order=append(j.order,step);manifest=append(manifest,step,method,route) }
journalNeed(len(j.allowed)>0,"Only write workflows need a restart journal");j.header=[]string{"H","1",base,workspace,slug,job,inputFingerprint,journalDigest(journalStrings(manifest))};journalStrings(j.header)
j.file,err=os.OpenFile(j.lockPath,os.O_RDWR|os.O_CREATE|os.O_EXCL,0600);if err!=nil { if os.IsExist(err){panic(journalRefusal{"This journal is locked; do not overlap jobs or steal a stale lock"})};panic(err) };j.owned=true
defer func(){ if observed:=recover();observed!=nil { j.Close();panic(observed) } }()
random:=make([]byte,16);if _,err=io.ReadFull(rand.Reader,random);err!=nil{panic(err)};j.owner=hex.EncodeToString(random);if err=journalWriteAll(j.file,[]byte(j.owner));err!=nil{panic(err)};j.identity,err=j.file.Stat();if err!=nil{panic(err)}
info,err:=os.Lstat(path);if err!=nil&&!os.IsNotExist(err){panic(err)};exists:=err==nil;if exists{journalNeed(info.Mode()&os.ModeSymlink==0,"Choose a private regular journal file")};journalNeed(mode!="resume"||exists,"Journal missing: stop and reconcile lost state before starting a new logical job");journalNeed(mode!="new"||!exists,"Journal exists; use resume for the same logical job");if mode=="new"{raw:=append([]byte(journalPreamble),journalFrame(j.header)...);if err=journalWriteFile(path,os.O_WRONLY|os.O_CREATE|os.O_EXCL,raw);err!=nil{panic(err)}}
raw,err:=os.ReadFile(path);if err!=nil{panic(err)};records:=journalDecode(raw);journalNeed(len(records)>0&&stringsEqual(records[0],j.header),"Journal workspace/base/guide/job/input binding differs");for _,record:=range records[1:]{j.apply(record)};for step:=range j.intents{_,ok:=j.savedValues[step];journalNeed(ok,"Saved intent lacks ACK; stop and reconcile before retry")};return j
}
func stringsEqual(left,right []string) bool { if len(left)!=len(right){return false};for i,value:=range left{if value!=right[i]{return false}};return true }
func (j *guideJournal) apply(record []string) {
journalNeed(len(record)>0,"Empty journal record")
if record[0]=="I" { journalNeed(len(record)==6,"Invalid intent shape");step,method,route,fingerprint,key:=record[1],record[2],record[3],record[4],record[5];_,exists:=j.intents[step];expected,allowed:=j.allowed[step];_,adopted:=j.adoptedValues[step];pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}}
journalNeed(journalMatch(step,"[a-z][a-z0-9_-]*")&&!exists&&!adopted&&allowed&&expected==[2]string{method,route}&&journalMatch(fingerprint,"[0-9A-F]{64}")&&!pending,"Invalid, future or repeated intent");journalNeed(method=="POST"&&journalMatch(key,"[0-9a-f]{32}")||method!="POST"&&key=="","Invalid persisted action key");j.intents[step]=map[string]string{"method":method,"path":route,"request_fingerprint":fingerprint,"idempotency_key":key}
}else if record[0]=="A" { journalNeed(len(record)>=3,"Invalid ACK shape");step,text:=record[1],record[2];count,err:=strconv.ParseUint(text,10,64);_,prior:=j.intents[step];_,done:=j.savedValues[step];journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==1&&count==uint64((len(record)-3)/2)&&prior&&!done,"ACK without exactly one prior intent");names:=[]string{};for i:=3;i<len(record);i+=2{names=append(names,record[i])};ordered:=append([]string{},names...);sort.Strings(ordered);journalNeed(stringsEqual(names,ordered),"ACK names must be sorted");saved:=map[string]string{};for i,name:=range names{_,exists:=saved[name];journalNeed(!exists&&journalMatch(name,"[a-z][a-z0-9_]*")&&name!="api_key"&&name!="exhibitday_api_key","ACK names must be unique secret-free identifiers");saved[name]=record[4+2*i]};j.savedValues[step]=saved
}else if record[0]=="S" {
journalNeed(len(record)>=6,"Invalid read-adoption shape");step,method,route,readFingerprint,text:=record[1],record[2],record[3],record[4],record[5];completed:=map[string]bool{};for name:=range j.savedValues{completed[name]=true};for name:=range j.adoptedValues{completed[name]=true};prefix:=len(completed)<len(j.order);if prefix{for _,name:=range j.order[:len(completed)]{if !completed[name]{prefix=false}}};pending:=false;for name:=range j.intents{if _,ok:=j.savedValues[name];!ok{pending=true}};journalNeed(prefix&&!pending&&step==j.order[len(completed)],"Adopt only the exact next setup action without any pending intent")
target:=j.allowed[step];expected:="";if target==[2]string{"POST","/v1/events"}||step=="update_event"&&target==[2]string{"PATCH","/v1/events"}{expected="/v1/events/info"}else if target==[2]string{"POST","/v1/tasks/sections"}{expected="/v1/tasks/sections/info"};journalNeed(method=="GET"&&expected!=""&&route==expected,"Adoption requires the exact source-bound single Event or section read")
count,err:=strconv.ParseUint(text,10,64);journalNeed(journalMatch(text,"0|[1-9][0-9]*")&&err==nil&&len(record)%2==0&&count==uint64((len(record)-6)/2),"Invalid read-adoption field count");names:=[]string{};for i:=6;i<len(record);i+=2{names=append(names,record[i])};fields:=[]string{"event_id","id","name"};if expected=="/v1/events/info"{fields=[]string{"id","integration_metadata_field_1"}};journalNeed(stringsEqual(names,fields),"Read-adoption fields must match the exact source tuple");saved:=map[string]string{};for i,name:=range names{saved[name]=record[7+2*i]}
for _,name:=range []string{"id","event_id"}{if value,ok:=saved[name];ok{parsed,e:=strconv.ParseInt(value,10,64);journalNeed(journalMatch(value,"[1-9][0-9]*")&&e==nil&&parsed>0,"Read-adoption IDs must be exact positive Int64 strings")}};for _,name:=range fields{journalNeed(name=="id"||name=="event_id"||saved[name]!="","Read-adoption material must be complete and fingerprint-bound")};journalNeed(readFingerprint==journalFingerprint(saved),"Read-adoption material must be complete and fingerprint-bound");j.adoptedValues[step]=saved
}else{panic(journalRefusal{"Unknown journal transition"})}
}
func (j *guideJournal) requireActive() {
journalNeed(j.owned&&j.file!=nil&&j.identity!=nil&&!j.tainted,"Journal is closed or IO outcome needs reconciliation");info,err:=os.Lstat(j.lockPath);if err!=nil{panic(err)};journalNeed(os.SameFile(j.identity,info),"Journal lock replaced; stop without deleting it");raw,err:=os.ReadFile(j.lockPath);if err!=nil{panic(err)};journalNeed(string(raw)==j.owner,"Journal lock token changed; stop without deleting it")
}
func (j *guideJournal) append(record []string) { j.requireActive();raw:=journalFrame(record);if err:=journalWriteFile(j.path,os.O_WRONLY|os.O_APPEND,raw);err!=nil{j.tainted=true;panic(err)} }
func (j *guideJournal) Acknowledged(step string) bool {j.requireActive();_,ok:=j.savedValues[step];return ok}
func (j *guideJournal) Saved(step string) map[string]string {j.requireActive();value,ok:=j.savedValues[step];journalNeed(ok,"No acknowledged state exists");return journalCopy(value)}
func (j *guideJournal) Completed(step string) bool {j.requireActive();_,a:=j.savedValues[step];_,s:=j.adoptedValues[step];return a||s}
func (j *guideJournal) Adopted(step string) bool {j.requireActive();_,ok:=j.adoptedValues[step];return ok}
func (j *guideJournal) Recorded(step string) map[string]string {j.requireActive();if value,ok:=j.savedValues[step];ok{return journalCopy(value)};value,ok:=j.adoptedValues[step];journalNeed(ok,"No completed write or read-adoption exists");return journalCopy(value)}
func (j *guideJournal) Adopt(step,method,route string,saved map[string]string) {j.requireActive();record:=[]string{"S",step,method,route,journalFingerprint(saved),strconv.Itoa(len(saved))};names:=[]string{};for name:=range saved{names=append(names,name)};sort.Strings(names);for _,name:=range names{record=append(record,name,saved[name])};previous:=journalCopyStates(j.adoptedValues);func(){defer func(){j.adoptedValues=previous}();j.apply(record);journalStrings(record)}();j.append(record);j.apply(record)}
func (j *guideJournal) Begin(step,method,route,requestFingerprint string) map[string]string {
j.requireActive();_,exists:=j.intents[step];journalNeed(!exists,"Never blindly repeat an existing action");key:="";if method=="POST"{raw:=make([]byte,16);if _,err:=io.ReadFull(rand.Reader,raw);err!=nil{panic(err)};key=hex.EncodeToString(raw)};record:=[]string{"I",step,method,route,requestFingerprint,key}
previous:=journalCopyStates(j.intents);func(){defer func(){j.intents=previous}();j.apply(record)}();j.append(record);j.apply(record);return journalCopy(j.intents[step])
}
func (j *guideJournal) Acknowledge(step string,saved map[string]string) {
j.requireActive();record:=[]string{"A",step,strconv.Itoa(len(saved))};names:=make([]string,0,len(saved));for name:=range saved{names=append(names,name)};sort.Strings(names);for _,name:=range names{record=append(record,name,saved[name])};previous:=journalCopyStates(j.savedValues);func(){defer func(){j.savedValues=previous}();j.apply(record);journalStrings(record)}();j.append(record);j.apply(record)
}
func (j *guideJournal) Close() {
if !j.owned{return};if j.tainted{err:=j.file.Close();j.file=nil;j.owned=false;if err!=nil{panic(err)};return}
func(){defer func(){if observed:=recover();observed!=nil{j.file.Close();j.file=nil;j.owned=false;panic(observed)}}();j.requireActive()}();if err:=j.file.Close();err!=nil{j.file=nil;j.owned=false;panic(err)};j.file=nil;j.owned=false;if err:=os.Remove(j.lockPath);err!=nil{panic(err)}
}
func journal_values(value any)map[string]string{fields,ok:=value.(map[string]any);journalNeed(ok,"Saved/fingerprint values need an explicit object");result:=map[string]string{};for name,item:=range fields{text,valid:=item.(string);journalNeed(valid,"Saved/fingerprint values must be exact strings");result[name]=text};return result}
func journal_object(fields map[string]string)any{result:=map[string]any{};for name,value:=range fields{result[name]=value};return result}
func journal_acknowledge(job *guideJournal,step string,saved any){job.Acknowledge(step,journal_values(saved))}
func journal_acknowledged(job *guideJournal,step string)bool{return job.Acknowledged(step)}
func journal_adopt(job *guideJournal,step,method,path string,saved any){job.Adopt(step,method,path,journal_values(saved))}
func journal_begin(job *guideJournal,step,method,path,requestFingerprint string)any{return journal_object(job.Begin(step,method,path,requestFingerprint))}
func journal_completed(job *guideJournal,step string)bool{return job.Completed(step)}
func journal_fingerprint(value any)string{return journalFingerprint(journal_values(value))}
func journal_recorded(job *guideJournal,step string)any{return journal_object(job.Recorded(step))}
func not_value(value bool)bool{return !value}
func open_journal(path,base,workspace,slug,job,inputFingerprint string,manifest any,mode string)*guideJournal{rows,ok:=manifest.([]any);journalNeed(ok,"A closed write manifest is required");writes:=[][3]string{};for _,row:=range rows{fields,valid:=row.([]any);journalNeed(valid&&len(fields)==3,"Each write must bind step/method/path");var values [3]string;for index,item:=range fields{text,valid:=item.(string);journalNeed(valid,"Manifest values are exact strings");values[index]=text};writes=append(writes,values)};return openGuideJournal(path,base,workspace,slug,job,inputFingerprint,writes,mode)}
func optional(name,fallback string)string{value:=os.Getenv(name);if value==""{return fallback};return value}
func page_size(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};size,err:=strconv.ParseInt(value,10,32);if !valid||err!=nil||size<=0{panic("Page size must be a positive int32")};return value}
func parse_json(value string)any{
decoder:=json.NewDecoder(strings.NewReader(value));decoder.UseNumber();var read func()any
read=func()any{token,err:=decoder.Token();if err!=nil{panic(err)};if delimiter,ok:=token.(json.Delim);ok{
if delimiter=='{'{result:=map[string]any{};for decoder.More(){key,err:=decoder.Token();if err!=nil{panic(err)};name,ok:=key.(string);if !ok{panic("Expected JSON property")};if _,exists:=result[name];exists{panic("Duplicate JSON input property")};result[name]=read()};end,err:=decoder.Token();if err!=nil||end!=json.Delim('}'){panic("Incomplete JSON object")};return result}
if delimiter=='['{result:=[]any{};for decoder.More(){result=append(result,read())};end,err:=decoder.Token();if err!=nil||end!=json.Delim(']'){panic("Incomplete JSON array")};return result};panic("Unexpected JSON delimiter")
};return token};result:=read();if _,err:=decoder.Token();err!=io.EOF{panic("Use one complete JSON input")};return result
}
func positive_id(value string)string{valid:=len(value)>0&&value[0]!='0';for _,ch:=range value{valid=valid&&ch>='0'&&ch<='9'};id,err:=strconv.ParseInt(value,10,64);if !valid||err!=nil||id<=0{panic("Use a positive record ID")};return value}
func print_value(value any){if result,ok:=value.(string);ok{fmt.Println(result);return};raw,err:=json.Marshal(value);if err!=nil{panic(err)};fmt.Println(string(raw))}
func require_condition(value bool,message string){if !value{panic(message)}}
func response_status(value result)string{return strconv.Itoa(value.status)}
func single(value any)any{rows:=items(value);if len(rows)!=1{panic("Expected exactly one selected record")};return rows[0]}
func validate_crm_event_inputs(key, name, start, end string) {
space := func(c rune) bool {
return c >= 9 && c <= 13 || c == 32 || c == 0x85 || c == 0xA0 || c == 0x1680 ||
c >= 0x2000 && c <= 0x200A || c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F || c == 0x3000
}
checkText := func(value, label string, limit int) {
journalNeed(utf8.ValidString(value), "Use valid UTF-8 for "+label)
journalNeed(value != "" && strings.TrimFunc(value,space) == value, "Remove whitespace at the start or end of "+label)
units := 0
for _, character := range value { units++; if character > 0xFFFF { units++ } }
journalNeed(units <= limit, fmt.Sprintf("%s exceeds %d UTF-16 code units",label,limit))
}
checkDate := func(value,label string) {
const format = "2006-01-02"
date,err := time.Parse(format,value)
journalNeed(err == nil && date.Format(format) == value && date.Year() >= 1753,
label+" must be a calendar date in YYYY-MM-DD on or after 1753-01-01")
}
checkText(name,"EXHIBITDAY_EVENT_NAME",500)
checkText(key,"EXHIBITDAY_EXTERNAL_EVENT_KEY",3000)
journalNeed(!strings.ContainsAny(name,"<>\r\n") && !strings.EqualFold(name,"null"), "Use plain, single-line EXHIBITDAY_EVENT_NAME text other than null")
checkDate(start,"EXHIBITDAY_START_DATE")
checkDate(end,"EXHIBITDAY_END_DATE")
journalNeed(end >= start,"EXHIBITDAY_END_DATE must be on or after EXHIBITDAY_START_DATE")
}
func workflow() {
external_event_key := required("EXHIBITDAY_EXTERNAL_EVENT_KEY")
desired_event_name := required("EXHIBITDAY_EVENT_NAME")
desired_start_date := required("EXHIBITDAY_START_DATE")
desired_end_date := required("EXHIBITDAY_END_DATE")
desired_dates_json := required("EXHIBITDAY_EXHIBIT_DATES_JSON")
desired_section_name := optional("EXHIBITDAY_TASK_SECTION_NAME", "Pre-event planning")
setup_page_size := page_size(optional("EXHIBITDAY_PAGE_SIZE", "100"))
desired_setup_dates := items(parse_json(desired_dates_json))
validate_crm_event_inputs(external_event_key, desired_event_name, desired_start_date, desired_end_date)
journal_path := required("EXHIBITDAY_JOURNAL")
stable_job_id := required("EXHIBITDAY_JOB_ID")
job_mode := optional("EXHIBITDAY_JOB_MODE", "resume")
setup_workspace_response := call("workspace_binding", map[string]string{}, nil, "")
require_condition(equal(response_status(setup_workspace_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_workspace := setup_workspace_response.body
owned_workspace_id := positive_id(text(field(setup_workspace, "id")))
setup_input_fingerprint := journal_fingerprint(map[string]any{"workflow_contract_sha256": "19097A09AE2D22C1AF56F5D4FBD9B72F524E5EC195434BC315834CC8C2417C32", "external_event_key": external_event_key, "name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "section_name": desired_section_name, "dates": desired_dates_json})
func() {
setup_job := open_journal(journal_path, "https://api.exhibitday.com/v1", owned_workspace_id, "event-setup-crm", stable_job_id, setup_input_fingerprint, []any{[]any{"create_event", "POST", "/v1/events"}, []any{"update_event", "PATCH", "/v1/events"}, []any{"create_section", "POST", "/v1/tasks/sections"}, []any{"save_dates", "PATCH", "/v1/events/dates"}}, job_mode)
defer setup_job.Close()
setup_event_id := ""
setup_section_id := ""
recorded_section_name := desired_section_name
if journal_completed(setup_job, "create_event") {
recorded_event := journal_recorded(setup_job, "create_event")
setup_event_id = positive_id(text(field(recorded_event, "id")))
require_condition(equal(text(field(recorded_event, "integration_metadata_field_1")), external_event_key), "The journal's completed Event differs from this external key.")
} else {
event_search_offset := "0"
event_search_query := map[string]string{"filter_by_integration_metadata_field_1": external_event_key, "$limit": setup_page_size}
for true {
event_search_query["$offset"] = event_search_offset
event_search_response := call("find_existing", event_search_query, nil, "")
require_condition(equal(response_status(event_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
event_search_page := event_search_response.body
event_search_rows := items(field(event_search_page, "list_data"))
require_condition(equal(text(field(event_search_page, "records_found")), text(count(event_search_rows))), "records_found differs from this complete page's rows.")
require_condition(is_present(text(field(event_search_page, "total_records"))), "The search wrapper needs total_records.")
require_condition(either(equal(field(event_search_page, "has_more"), true), equal(field(event_search_page, "has_more"), false)), "Expected a Boolean has_more value.")
for _, event_search_row := range items(event_search_rows) {
if equal(text(field(event_search_row, "integration_metadata_field_1")), external_event_key) {
event_search_candidate_id := positive_id(text(field(event_search_row, "id")))
if is_present(setup_event_id) {
require_condition(equal(setup_event_id, event_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.")
}
setup_event_id = event_search_candidate_id
}
}
if equal(field(event_search_page, "has_more"), false) {
break
}
require_condition(not_value(is_empty(event_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.")
event_search_offset = add_offset(event_search_offset, count(event_search_rows))
}
if not_value(is_present(setup_event_id)) {
event_write_fingerprint := journal_fingerprint(map[string]any{"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key})
event_intent := journal_begin(setup_job, "create_event", "POST", "/v1/events", event_write_fingerprint)
event_create_response := call("create_event", map[string]string{}, map[string]any{"name": desired_event_name, "start_date": desired_start_date, "end_date": desired_end_date, "integration_metadata_field_1": external_event_key}, text(field(event_intent, "idempotency_key")))
require_condition(equal(response_status(event_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
created_event := event_create_response.body
setup_event_id = positive_id(text(field(created_event, "id")))
require_condition(equal(text(field(created_event, "integration_metadata_field_1")), external_event_key), "The created Event's external key differs; preserve the pending intent and reconcile.")
require_condition(both(is_present(text(field(created_event, "name"))), both(is_present(text(field(created_event, "start_date"))), is_present(text(field(created_event, "end_date"))))), "The Event acknowledgement omitted its saved name or main dates.")
journal_acknowledge(setup_job, "create_event", map[string]any{"id": setup_event_id, "integration_metadata_field_1": external_event_key})
}
}
event_confirmation_response := call("confirm_event", map[string]string{"id": setup_event_id, "$include_record_revision": "true"}, nil, "")
require_condition(equal(response_status(event_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
confirmed_setup_event := event_confirmation_response.body
require_condition(both(equal(text(field(confirmed_setup_event, "id")), setup_event_id), equal(text(field(confirmed_setup_event, "integration_metadata_field_1")), external_event_key)), "The captured Event is missing or rebound; stop instead of searching for or creating a replacement.")
if not_value(journal_completed(setup_job, "create_event")) {
journal_adopt(setup_job, "create_event", "GET", "/v1/events/info", map[string]any{"id": text(field(confirmed_setup_event, "id")), "integration_metadata_field_1": text(field(confirmed_setup_event, "integration_metadata_field_1"))})
}
setup_event_revision := text(field(confirmed_setup_event, "record_revision"))
require_condition(is_present(setup_event_revision), "Read the selected Event with its revision before comparing or updating it.")
require_condition(both(both(is_present(text(field(confirmed_setup_event, "name"))), is_present(text(field(confirmed_setup_event, "start_date")))), is_present(text(field(confirmed_setup_event, "end_date")))), "The selected Event must return its current name, start date and end date.")
if journal_completed(setup_job, "update_event") {
recorded_event_update := journal_recorded(setup_job, "update_event")
require_condition(both(equal(text(field(recorded_event_update, "id")), setup_event_id), equal(text(field(recorded_event_update, "integration_metadata_field_1")), external_event_key)), "The recorded Event update has a different identity. Stop and reconcile.")
require_condition(both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)), "The Event name or main dates changed after this job checked them. Review the current Event before writing again.")
} else {
if both(both(equal(text(field(confirmed_setup_event, "name")), desired_event_name), equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)), equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)) {
journal_adopt(setup_job, "update_event", "GET", "/v1/events/info", map[string]any{"id": setup_event_id, "integration_metadata_field_1": external_event_key})
} else {
require_condition(not_value(journal_acknowledged(setup_job, "create_event")), "The Event created by this job differs from the requested values. Inspect the saved Event before starting another update.")
event_update_body := map[string]any{"id": setup_event_id, "expected_revision": setup_event_revision}
if not_value(equal(text(field(confirmed_setup_event, "name")), desired_event_name)) {
event_update_body["name"] = desired_event_name
}
if not_value(equal(text(field(confirmed_setup_event, "start_date")), desired_start_date)) {
event_update_body["start_date"] = desired_start_date
}
if not_value(equal(text(field(confirmed_setup_event, "end_date")), desired_end_date)) {
event_update_body["end_date"] = desired_end_date
}
event_update_fingerprint := journal_fingerprint(event_update_body)
journal_begin(setup_job, "update_event", "PATCH", "/v1/events", event_update_fingerprint)
event_update_response := call("update_event", map[string]string{}, event_update_body, "")
require_condition(equal(response_status(event_update_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
event_update_ack := event_update_response.body
event_updated_revision := text(field(event_update_ack, "record_revision"))
require_condition(is_present(event_updated_revision), "The conditional Event update needs its returned revision. Reconcile the pending request before continuing.")
journal_acknowledge(setup_job, "update_event", map[string]any{"id": setup_event_id, "integration_metadata_field_1": external_event_key, "record_revision": event_updated_revision})
}
}
event_update_verify_response := call("verify_event_update", map[string]string{"id": setup_event_id}, nil, "")
require_condition(equal(response_status(event_update_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
verified_setup_event := event_update_verify_response.body
require_condition(both(both(equal(text(field(verified_setup_event, "id")), setup_event_id), equal(text(field(verified_setup_event, "integration_metadata_field_1")), external_event_key)), both(both(equal(text(field(verified_setup_event, "name")), desired_event_name), equal(text(field(verified_setup_event, "start_date")), desired_start_date)), equal(text(field(verified_setup_event, "end_date")), desired_end_date))), "The Event's current identity, name or main dates differ. Inspect the Event before continuing with setup.")
if journal_completed(setup_job, "create_section") {
recorded_section := journal_recorded(setup_job, "create_section")
setup_section_id = positive_id(text(field(recorded_section, "id")))
require_condition(equal(text(field(recorded_section, "event_id")), setup_event_id), "The recorded Task Section belongs to a different Event.")
recorded_section_name = text(field(recorded_section, "name"))
} else {
section_search_offset := "0"
section_search_query := map[string]string{"filter_by_event_id": setup_event_id, "$limit": setup_page_size}
for true {
section_search_query["$offset"] = section_search_offset
section_search_response := call("find_section", section_search_query, nil, "")
require_condition(equal(response_status(section_search_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
section_search_page := section_search_response.body
section_search_rows := items(field(section_search_page, "list_data"))
require_condition(equal(text(field(section_search_page, "records_found")), text(count(section_search_rows))), "records_found differs from this complete page's rows.")
require_condition(is_present(text(field(section_search_page, "total_records"))), "The search wrapper needs total_records.")
require_condition(either(equal(field(section_search_page, "has_more"), true), equal(field(section_search_page, "has_more"), false)), "Expected a Boolean has_more value.")
for _, section_search_row := range items(section_search_rows) {
require_condition(equal(text(field(section_search_row, "event_id")), setup_event_id), "A section search row belongs to a different Event; stop before adopting or creating anything.")
if equal(text(field(section_search_row, "name")), desired_section_name) {
section_search_candidate_id := positive_id(text(field(section_search_row, "id")))
if is_present(setup_section_id) {
require_condition(equal(setup_section_id, section_search_candidate_id), "More than one matching record exists. Reconcile the ambiguity instead of selecting one or creating another.")
}
setup_section_id = section_search_candidate_id
}
}
if equal(field(section_search_page, "has_more"), false) {
break
}
require_condition(not_value(is_empty(section_search_rows)), "An empty search page has has_more=true. Stop and reconcile the search.")
section_search_offset = add_offset(section_search_offset, count(section_search_rows))
}
if not_value(is_present(setup_section_id)) {
section_write_fingerprint := journal_fingerprint(map[string]any{"event_id": setup_event_id, "name": desired_section_name})
section_intent := journal_begin(setup_job, "create_section", "POST", "/v1/tasks/sections", section_write_fingerprint)
section_create_response := call("create_section", map[string]string{}, map[string]any{"event_id": setup_event_id, "name": desired_section_name}, text(field(section_intent, "idempotency_key")))
require_condition(equal(response_status(section_create_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
created_section := section_create_response.body
setup_section_id = positive_id(text(field(created_section, "id")))
require_condition(equal(text(field(created_section, "event_id")), setup_event_id), "The created Task Section belongs to a different Event; preserve the pending intent.")
recorded_section_name = text(field(created_section, "name"))
require_condition(is_present(recorded_section_name), "The Task Section acknowledgement needs its actual saved name.")
journal_acknowledge(setup_job, "create_section", map[string]any{"id": setup_section_id, "event_id": setup_event_id, "name": recorded_section_name})
}
}
section_confirmation_response := call("confirm_section", map[string]string{"id": setup_section_id}, nil, "")
require_condition(equal(response_status(section_confirmation_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
confirmed_setup_section := section_confirmation_response.body
require_condition(both(equal(text(field(confirmed_setup_section, "id")), setup_section_id), both(equal(text(field(confirmed_setup_section, "event_id")), setup_event_id), equal(text(field(confirmed_setup_section, "name")), recorded_section_name))), "The captured Task Section is missing, renamed or rebound; stop instead of creating a replacement.")
if not_value(journal_completed(setup_job, "create_section")) {
journal_adopt(setup_job, "create_section", "GET", "/v1/tasks/sections/info", map[string]any{"event_id": text(field(confirmed_setup_section, "event_id")), "id": text(field(confirmed_setup_section, "id")), "name": text(field(confirmed_setup_section, "name"))})
}
setup_dates_response := call("read_dates", map[string]string{"event_id": setup_event_id, "filter_by_date_type_id": "1", "$include_record_revision": "true"}, nil, "")
require_condition(equal(response_status(setup_dates_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_page := setup_dates_response.body
require_condition(both(equal(text(field(setup_dates_page, "records_found")), "1"), both(equal(text(field(setup_dates_page, "total_records")), "1"), equal(field(setup_dates_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.")
setup_dates_group := single(field(setup_dates_page, "list_data"))
require_condition(both(equal(text(field(setup_dates_group, "event_id")), setup_event_id), equal(text(field(setup_dates_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.")
setup_dates_revision := text(field(setup_dates_group, "record_revision"))
require_condition(is_present(setup_dates_revision), "Read the actual selected group revision before replacing it.")
if journal_completed(setup_job, "save_dates") {
recorded_dates := journal_recorded(setup_job, "save_dates")
require_condition(both(equal(text(field(recorded_dates, "event_id")), setup_event_id), equal(text(field(recorded_dates, "date_type_id")), "1")), "The recorded Dates acknowledgement belongs to another Event or group.")
} else {
setup_dates_fingerprint := journal_fingerprint(map[string]any{"event_id": setup_event_id, "date_type_id": "1", "dates": desired_dates_json, "expected_revision": setup_dates_revision})
journal_begin(setup_job, "save_dates", "PATCH", "/v1/events/dates", setup_dates_fingerprint)
setup_dates_save_response := call("save_dates", map[string]string{}, map[string]any{"event_id": setup_event_id, "date_type_id": "1", "dates": desired_setup_dates, "expected_revision": setup_dates_revision}, "")
require_condition(equal(response_status(setup_dates_save_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_ack := setup_dates_save_response.body
setup_dates_saved_revision := text(field(setup_dates_ack, "record_revision"))
require_condition(is_present(setup_dates_saved_revision), "The checked Dates save needs its actual returned revision.")
journal_acknowledge(setup_job, "save_dates", map[string]any{"event_id": setup_event_id, "date_type_id": "1", "record_revision": setup_dates_saved_revision})
}
setup_dates_verify_response := call("verify_dates", map[string]string{"event_id": setup_event_id, "filter_by_date_type_id": "1"}, nil, "")
require_condition(equal(response_status(setup_dates_verify_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_dates_verify_page := setup_dates_verify_response.body
require_condition(both(equal(text(field(setup_dates_verify_page, "records_found")), "1"), both(equal(text(field(setup_dates_verify_page, "total_records")), "1"), equal(field(setup_dates_verify_page, "has_more"), false))), "Expected one complete selected Dates group, without another page.")
setup_dates_verify_group := single(field(setup_dates_verify_page, "list_data"))
require_condition(both(equal(text(field(setup_dates_verify_group, "event_id")), setup_event_id), equal(text(field(setup_dates_verify_group, "date_type_id")), "1")), "The Dates group belongs to another Event or type.")
require_condition(deep_equal(field(setup_dates_verify_group, "dates"), desired_setup_dates), "The saved normalized Dates list differs from the supplied canonical list. Inspect it; do not automatically restore or repeat the update.")
setup_event_readback_response := call("event_readback", map[string]string{"id": setup_event_id}, nil, "")
require_condition(equal(response_status(setup_event_readback_response), "200"), "Expected the endpoint's documented HTTP200 response; do not infer an acknowledgement from another status.")
setup_event_readback := setup_event_readback_response.body
require_condition(both(equal(text(field(setup_event_readback, "id")), setup_event_id), equal(text(field(setup_event_readback, "integration_metadata_field_1")), external_event_key)), "Final Event readback is missing or rebound; earlier steps remain saved.")
require_condition(both(both(equal(text(field(setup_event_readback, "name")), desired_event_name), equal(text(field(setup_event_readback, "start_date")), desired_start_date)), equal(text(field(setup_event_readback, "end_date")), desired_end_date)), "The Event name or main dates changed before final readback. Inspect the Event before starting another update.")
planning_section_present := false
for _, setup_event_section := range items(items(field(setup_event_readback, "task_sections"))) {
if equal(text(field(setup_event_section, "id")), setup_section_id) {
planning_section_present = true
}
}
require_condition(planning_section_present, "The Event's current Task Sections do not include the recorded section; inspect it rather than creating another.")
print_value(map[string]any{"event_id": setup_event_id, "task_section_id": setup_section_id, "dates_verified": "true"})
}()
}
func header_key(value string)string{for _,ch:=range value{if ch<32||ch>126{panic("Use the API key as one ASCII header value without control characters")}};return value}
func main(){apiKey=header_key(required("EXHIBITDAY_API_KEY"));if err:=json.Unmarshal([]byte(specification),&spec);err!=nil{panic(err)};workflow()}
Example response
{
"id": 5001,
"exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001",
"name": "Spring Expo 2030",
"start_date": "2030-01-14",
"end_date": "2030-01-16",
"participation_type_id": 1,
"participation_type": "Committed",
"format_id": 1,
"format": "In-Person",
"star_rating": 0,
"tags": [
"International",
"Field Marketing"
],
"website_url": "",
"venue_name": "",
"venue_address": "",
"venue_location_display_name": "",
"venue_address_latitude": "",
"venue_address_longitude": "",
"booth_size": "",
"booth_number": "",
"booth_reservation_status_id": 1,
"booth_reservation_status": "Need to Reserve",
"booth_reserve_by_date": "",
"booth_date_reserved": "",
"budget_booth_reservation": 0.00,
"budget_booth_services": 0.00,
"budget_attendee_registrations": 0.00,
"budget_travel": 0.00,
"budget_giveaways": 0.00,
"budget_shipments": 0.00,
"budget_event_activities": 0.00,
"budget_misc_expenses": 0.00,
"budget_sponsorships": 0.00,
"total_sum_event_budgets": 0.00,
"booth_reservation_cost": {
"amount": 125.50,
"cost_center_breakdown": [
{
"cost_center_id": 34567,
"cost_center": "Marketing",
"charge": 75.50
},
{
"cost_center_id": 34568,
"cost_center": "Operations",
"charge": 50.00
}
]
},
"cost_booth_reservation": 125.50,
"booth_reservation_payment_status_id": 0,
"booth_reservation_payment_status": "",
"booth_reservation_payment_due_date": null,
"booth_reservation_next_payment_due_date": null,
"booth_reservation_payment_notes": null,
"booth_reservation_invoice_attachment": {
"id": 175001,
"filename": "booth-reservation-invoice.pdf",
"attachment_created_timestamp": "2027-01-30T12:00:00Z"
},
"cost_booth_services": 0.00,
"cost_attendee_registrations": 0.00,
"cost_travel_reservations": 0.00,
"cost_giveaways": 0.00,
"cost_shipments": 0.00,
"cost_event_activities": 0.00,
"cost_misc_expenses": 100.50,
"cost_sponsorships": 0.00,
"total_sum_event_costs": 226.00,
"event_notes": "",
"booth_notes": "",
"budget_notes": "",
"roi_notes": "",
"roi_num_leads": 0,
"roi_num_impressions_booth": 0,
"roi_num_impressions_sponsorships": 0,
"roi_num_impressions_media": 0,
"roi_num_meetings_existing_customers": 0,
"roi_num_meetings_new_customers": 0,
"roi_amount_actual_sales": 0.00,
"roi_amount_potential_sales": 0.00,
"roo_score": null,
"event_created_timestamp": "2029-12-01T17:00:00Z",
"event_last_update_timestamp": "2030-01-02T17:00:00Z",
"event_created_by": null,
"custom_fields": [
{
"label": "Integration status",
"value": "Ready",
"notes": "",
"field_name": "custom_67890",
"field_type": "Text (Single-line)",
"field_event_tab": "Info"
},
{
"label": "Setup instructions",
"value": "Place the display beside the entrance.",
"notes": "",
"field_name": "custom_67891",
"field_type": "Text (Single-line)",
"field_event_tab": "Booth"
}
],
"task_sections": [
{
"id": 6001,
"name": "Pre-event planning",
"display_rank": 0
},
{
"id": 6002,
"name": "Onsite follow-up",
"display_rank": 1
}
],
"tasks": [
{
"id": 7002,
"exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=7002",
"event_task_section_id": 6001,
"event_task_section": "Pre-event planning",
"display_rank": 1,
"name": "Confirm booth setup",
"due_date": "2030-01-12",
"assignee": {
"id": "11111111-2222-4333-8444-555555555555",
"first_name": "Jane",
"last_name": "Smith",
"display_name": "Jane Smith",
"email": "jane@example.invalid",
"type": "user",
"workspace_role": "team_member",
"is_active": true
},
"is_completed": false,
"task_completed_timestamp": null,
"task_created_timestamp": "2029-12-01T17:01:00Z",
"task_last_update_timestamp": "2029-12-01T17:01:00Z"
},
{
"id": 7003,
"exhibitday_url": "https://www.exhibitday.com/Workspace/TaskView/98765?tid=7003",
"event_task_section_id": 6002,
"event_task_section": "Onsite follow-up",
"display_rank": 2,
"name": "Prepare the staff schedule",
"due_date": "2030-01-13",
"assignee": {
"id": "66666666-7777-4888-8999-aaaaaaaaaaaa",
"first_name": "Alex",
"last_name": "Jordan",
"display_name": "Alex Jordan",
"email": "alex@example.invalid",
"type": "user",
"workspace_role": "team_member",
"is_active": true
},
"is_completed": false,
"task_completed_timestamp": null,
"task_created_timestamp": "2029-12-01T17:02:00Z",
"task_last_update_timestamp": "2029-12-01T17:02:00Z"
}
],
"misc_expenses_credits": [
{
"id": 8002,
"exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001&riType=8&riSub=0&riId=8002",
"description": "Conference meals",
"is_credit": false,
"cost": {
"amount": 125.50,
"cost_center_breakdown": [
{
"cost_center_id": 34567,
"cost_center": "Marketing",
"charge": 75.50
},
{
"cost_center_id": 34568,
"cost_center": "Operations",
"charge": 50.00
}
]
},
"notes": "",
"payment_due_date": null,
"payment_status": {
"id": 0,
"name": "Not Specified"
},
"next_payment_due_date": null,
"next_partial_payment_due_date": null,
"payment_notes": null,
"invoice_attachment": {
"id": 678002,
"filename": "expense-invoice.pdf",
"attachment_created_timestamp": "2027-01-30T12:00:00Z"
},
"event_misc_expense_credit_created_timestamp": "2029-12-01T17:00:00Z",
"event_misc_expense_credit_last_update_timestamp": "2029-12-01T17:00:00Z"
},
{
"id": 8003,
"exhibitday_url": "https://www.exhibitday.com/Workspace/Event/98765?eid=5001&riType=8&riSub=0&riId=8003",
"description": "Supplier refund",
"is_credit": true,
"cost": {
"amount": -25.00,
"cost_center_breakdown": [
{
"cost_center_id": 34567,
"cost_center": "Marketing",
"charge": -15.00
},
{
"cost_center_id": 34568,
"cost_center": "Operations",
"charge": -10.00
}
]
},
"notes": "",
"payment_due_date": null,
"payment_status": {
"id": 0,
"name": "Not Specified"
},
"next_payment_due_date": null,
"next_partial_payment_due_date": null,
"payment_notes": null,
"invoice_attachment": {
"id": 678003,
"filename": "expense-invoice.pdf",
"attachment_created_timestamp": "2027-01-30T12:00:00Z"
},
"event_misc_expense_credit_created_timestamp": "2029-12-01T17:00:00Z",
"event_misc_expense_credit_last_update_timestamp": "2029-12-01T17:00:00Z"
}
],
"integration_metadata_field_1": "crm:event:spring-expo-2030",
"integration_metadata_field_2": null,
"integration_metadata_field_3": null,
"integration_metadata_field_4": null,
"integration_metadata_field_5": null
}
{
"status_code": 400,
"status": "Bad Request",
"message": "HTTP method override is not supported.",
"error_code": "invalid_request",
"errors": [
"Send the documented HTTP method directly. X-HTTP-Method-Override cannot change a request's HTTP method."
],
"error_params": [
"X-HTTP-Method-Override"
],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 401,
"status": "Unauthorized",
"message": "No API key was provided. Send your key in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.",
"error_code": "missing_api_key",
"errors": [
"Copy the key from Workspace Settings > API & Integrations > API Access in ExhibitDay."
],
"error_params": [
"api_key"
],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 401,
"status": "Unauthorized",
"message": "The API key is not valid. Check that you copied the whole key from Workspace Settings > API & Integrations > API Access, then send it in the Authorization header as 'Bearer YOUR_API_KEY'. Alternatively, you can use the api_key parameter.",
"error_code": "invalid_api_key",
"errors": [
"Check that you sent the whole key. If it was regenerated, use the current key from Workspace Settings > API & Integrations > API Access."
],
"error_params": [
"api_key"
],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 401,
"status": "Unauthorized",
"message": "Access to the ExhibitDay API is not enabled for your workspace. Please contact support@exhibitday.com to enable API Access. Once access is enabled, send your key in the Authorization header as 'Bearer YOUR_API_KEY'.",
"error_code": "api_access_disabled",
"errors": [
"Nothing was read or changed."
],
"error_params": [
"api_key"
],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 404,
"status": "Not Found",
"message": "Event not found. Invalid Event ID: 12345.",
"error_code": "not_found",
"errors": [
"Event not found. Invalid Event ID: 12345."
],
"error_params": [
"id"
],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 409,
"status": "Conflict",
"message": "The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying.",
"error_code": "record_changed",
"errors": [
"The invoice attachment or its owning record changed or has conflicting saved information. Retrieve the current record before retrying."
],
"error_params": [],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 409,
"status": "Conflict",
"message": "The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying.",
"error_code": "record_changed",
"errors": [
"The Booth Reservation payment information changed or has an unsupported saved status. Retrieve the current Event before retrying."
],
"error_params": [],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 409,
"status": "Conflict",
"message": "The Event objective score changed or could not be read consistently. Retrieve the Event before retrying.",
"error_code": "record_changed",
"errors": [
"The Event objective score changed or could not be read consistently. Retrieve the Event before retrying."
],
"error_params": [],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 409,
"status": "Conflict",
"message": "The record was being changed while it was read, so no record_revision could be issued. Read it again.",
"error_code": "record_changed",
"errors": [
"The record was being changed while it was read, so no record_revision could be issued. Read it again."
],
"error_params": [
"$include_record_revision"
],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 429,
"status": "Too Many Requests",
"message": "Error 429 - Too Many Requests",
"error_code": "rate_limited",
"errors": [
"Error 429 - Too Many Requests"
],
"error_params": [],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 500,
"status": "Unexpected Internal Error",
"message": "An unexpected error occurred. Please try again later.",
"error_code": "internal_error",
"errors": [
"An unexpected error occurred. Please try again later."
],
"error_params": [],
"request_id": "0123456789abcdef0123456789abcdef"
}
{
"status_code": 500,
"status": "Unexpected Internal Error",
"message": "An unexpected error occurred. Please try again later.",
"error_code": "internal_error",
"errors": [
"Check whether your change was saved before trying again."
],
"error_params": [],
"request_id": "0123456789abcdef0123456789abcdef"
}
Things to keep in mind
- Use one CRM key per Event. ExhibitDay allows the same key on more than one Event.
- If two runs could create the same Event, run them one at a time.
- If the search finds more than one match, the program stops so you can check.
- Enter Exhibit Hall times in the Event's local time. ExhibitDay saves the time-zone label you send and keeps the times as entered.
- The Event and its Exhibit Hall dates are protected from overwrites separately.
If a run stops
- Each step saves on its own, so a stopped run may have saved some steps.
- Keep the journal private. It records what the program tried to save and which saves it confirmed.
- To continue a run with no unresolved save, use
EXHIBITDAY_JOB_MODE=resumewith the same job ID, journal path and inputs. - If a save stopped with a conflict, a lost response or a missing revision, check what was saved in ExhibitDay before running the program again.
- If you still need changes after checking the old run, set
EXHIBITDAY_JOB_MODE=newwith a new job ID and journal path. - Start a new job when your CRM sends new values.
- Run only one copy per journal.
- If a crash leaves a
.lockfile, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal.